The introduction of

(19.0205) In a mobile interactive project I worked on during The Double 11, I encountered a function of switching between App, wechat and H5 page environment to select Audio playback. During the test, there were many compatibility problems. There are a lot of knowledge worth exploring, and today we will take a look at the HTML5-Audio.

The Audio tag is used to define sounds, such as music or other Audio streams, and HTML5’s Audio tag has largely replaced Flash for playing music.

The default style

The default style of the Audio tag in the browser is shown in the following figure. One caveat is that you need to configure the controls property (whether to display the default control bar is the Audio tag’s control property), otherwise the style effect will not be displayed.

Audio Supported Audio file formats

1, OGG:

OGG is a new audio compression format, similar to MP3 and other music formats. OGG is completely free, open and patent free. The OGG file format can be continuously improved in size and sound quality without affecting older encoders or players.

2, MP3:

MP3 is an audio compression technology, its full name is Moving_Picture_Experts_Group_Audio_Layer_III (Moving Image Expert Compression Standard Audio Level 3), abbreviated as MP3. It is designed to dramatically reduce the amount of audio data. Music is compressed at 1:10 or even 1:12 into smaller files, and for most users the quality of the playback is not significantly worse than the original uncompressed audio.

3, WAV:

WAV is a sound file format developed by Microsoft. It is used to store audio information resources on the Windows platform. It is widely supported by the Windows platform and its applications.

Third, compatibility problems

Let’s look at compatibility from the following perspectives:

1. Compatibility of audio formats

Audio formats Chrome Firefox IE9 Opera Safari
OGG support support support support Does not support
MP3 support Does not support support Does not support support
WAV Does not support support Does not support support Does not support

Description:

By default, the Audio tag supports the major Audio file formats MP3, WAV, and OGG. Different browsers support different formats. The MP3 format has the best support.

WAV format has the best sound quality, but the file size is larger. MP3 compression rate is higher, high penetration rate, sound quality is worse than WAV. OGG and MP3 encode at the same Bit Rate, OGG is smaller, and OGG is free without paying royalties (which is popular among Chinese).

2. Compatibility between different browsers for HTML5 Audio tags

Description:

The Audio tag is available in newer browsers, but will be more compatible on mobile.

Four, use method

Properties, methods, and events that we often use:

1. Common attributes:

attribute Attribute values annotation
src url Url of the music being played (Firefox only supports OGG music, while IE9 only supports MP3 music. Chrome seems to support it all)
preload preload Preloading (loading or buffering audio while the page is loaded) is disabled if autoplay is used.
loop loop Loop for
controls controls Whether to display the default control bar (control button)
autoplay autoplay Automatically play

2. Common methods:

function role
load(a) Load audio and video software
play(a) Load and play audio or video files or restart suspended audio or video files
pause(a) Pause the currently playing audio

3. Common events:

The name of the event Event role
play Play and Autoplay play
pause The pause method is triggered
ended End of Current Playback
timeupdate When the current playback time is changed (common time handling during playback)
canplaythrough The song is fully loaded
canplay Buffered to the current playable state.

We can control playback with JS code:

let audio = document.getElementById('audio'); audio.load(); / / load the audio. Play (); / / play audio. Pause (); // Pause audio. Loop = true; // LoopCopy the code

V. Problems and Solutions:

Ok, let’s look at the compatibility of the Audio tag in detail:

1. How to solve the preloading problem

Status: Preload is not supported on safari and wechat on iOS.

Solution: ** Requires the user to actively trigger the Event ** to play.

Sample code:

$("#btn").click(function() {
    $("#audio").load();
})
Copy the code

2. How to solve the problem of switching multiple audio files

Status: At that time, different music playback was switched in the project. If the SRC of the Audio tag was changed, the music could not be played in iOS or the playback delay was too high.

Solution: The reason for this bug is that the audio file cannot be cached on the iOS system. Whenever a page accesses another audio file, the audio file is accessed from the network. Solution: You can declare multiple Audio tags in the page to pre-import the Audio files that need to be imported, and then call the corresponding files when playing the Audio files. The disadvantage of this scheme is that in iOS system, each Audio occupies one thread. If there are multiple Audio tags, it will occupy a lot of resources. Or combine multiple audio files into one file. When playing other audio files, you only need to call the corresponding time period of the merged audio file. Although tedious, it has good compatibility, you can refer to the audio merge tool (jsfiddle.net/aarongloege…

Sample code:

<audio src="" id="audio1"></audio>
<audio src="" id="audio2"></audio>
var audio1 = document.getElementById('audio1');
var audio2 = document.getElementById('audio2');
audio1.play();
audio2.play();
Copy the code

3. How to solve the auto-play problem

Status: Safari on iOS and some Android browsers do not support AutoPlay.

Solution: Guide the user to manually trigger the playback operation. For example, bind the TouchStart event to operate audio-play (), so you need to confirm this point when communicating with the product and testing students. If in the wechat environment can call the plug-in provided by wechat (jweixin-1.0.0.js).

Sample code:

wx.ready(function() {
    audio.play();
});
Copy the code

4. How to solve the problem of broadcast quantity

Status quo: An Audio tag can play only one Audio.

Solution: if you want to play multiple Audio at the same time, had to use multiple Audio tags, but must pay attention to this case, the browser is support multiple Audio broadcast on the same page, and the basic project scene an Audio broadcast only allowed, this must pay attention to control when you play the music stop other music playback.

Sample code:

<audio src="a.mp3" src="a.mp3"></audio>
<audio src="b.mp3" src="b.mp3"></audio>
<audio src="c.mp3" src="c.mp3"></audio>
Copy the code

5. How to solve the problem of audio mixing and playing on the mobile terminal

Status: In iOS Safari, Audio continues to loop when you close the browser window (go to background) or switch tabs. Audio stops when you close the browser TAB.

Solution: Use cyclic storage time to check if the user is on a web page. The timeUpdate event is triggered when the playback position of the Audio Audio changes.

Sample code:

var lastSeen;
var loop = function (){
    lastSeen = Date.now();
    setTimeout(loop, 50);
};
loop();

var music = document.getElementById('music');
music.addEventListener('timeupdate', function (){
    if(Date.now() - lastSeen > 100){
        this.pause();
    }
}, false);
Copy the code

6. How to solve the problem of continuous broadcasting

Status: When audio is playing on JDApp, the page is switched to the background or other applications. After music is paused, the music is switched to the original page, but the music does not continue to play.

Solution: determine whether under JDApp, if used in JDApp JDAppUnite call native methods callRouterModuleWithParams control audio to continue playing.

Sample code:

Function toOriginalChk(WVT, soundRouter) {if (WVT == 'notJdApp') {return; } else if (WVT = = wk 'a') {/ / notify native playback state window. Its. MessageHandlers. JDAppUnite. PostMessage ({' method ': 'callRouterModuleWithParams', 'params': JSON.stringify(soundRouter) }); } else if (wvt == 'ui') { window.JDAppUnite && window.JDAppUnite.callRouterModuleWithParams(JSON.stringify(soundRouter)); }}Copy the code

7. How to solve the initialization delay problem

Status: There is a delay of several seconds when initializing a new audio stream in iOS Safari.

Solution: The reason for this bug is that iOS needs to instantiate a new audio object, and then request the audio resource through the network. The audio resource can only be played after it is loaded. Solution: Load each file after the page is ready, and then call the Play method. By doing this, audio resources can be preloaded, and network requests can be made in advance, which can be optimized for specific business scenarios.

(3) Sample code:


$(function() {
    $("#audio1").load();
    $("#audio2").load();
})

Copy the code

8. How to solve the mute operation problem

What we see now: Ideally, users can mute audio by triggering events on relevant pages

Solution: Audio can be muted by setting the fraternal attribute, but the fraternal attribute is not supported in iOS 8 and below or IE9 and below.

Sample code:


$("#audio").muted = true

Copy the code

9. How to solve the loading problem

Status: If the play method fails to be called while the page is not loaded, in which case setting currentTime will throw an exception Failed to load resource: The server situates with a status of 404 ().

Solution: If you encounter such problems, you can check the network and audio size to eliminate them.

10. How to solve the problem of loop playing

Status: Loop properties are not supported on iOS until 5.

Solution: You can solve this problem by adding an event listener to an onEnded event and calling the Play method in that function.

Sample code:

var audio = document.getElementById('audio');
audio.play();

var onEnded = function() {
    this.play();
};

audio.addEventListener('ended', onEnded, false);
    
Copy the code

The HTML5 Audio tag gives us some extra information to specify which time period to play, by following the format (” # “) after the media file

<audio SRC ="audio. Mp3 #t=10,20"></audio> // SRC ="audio. Mp3 #t=10" (from 10s to 20s) // SRC ="audio. Mp3 #t=,10" (from the beginning to 10s)Copy the code

conclusion

Although there are many compatibility problems with the Audio tag provided by HTML5, Audio is still the general trend of HTML5 development and worth using in the mobile end. This article introduces how to use the Audio tag and the compatible version of Audio files and the compatibility of Audio in different environments and provides corresponding solutions. Finally, the plugin developed by myself is attached (github.com/jdf2e/audio…) , scan the QR code to visit:

The solution mentioned above can help you solve most of the problems. If you need to better avoid these Audio pits, you can refer to this JS plug-in. The method of use is as follows:

jdMusic.create([{
                src: 'https://jdch5.jd.com/yayoi/res/raw-assets/Sound/A.mp3',
                isloop: false,
                id: 'demo1',
                class: 'demo1',
                autoplay: false
            }, {
                src: 'https://jdch5.jd.com/yayoi/res/raw-assets/Sound/B.mp3',
                isloop: false,
                id: 'demo2',
                class: 'demo2',
                autoplay: true
            }]);
 jdMusic.play(0)
 jdMusic.pause()
Copy the code

reference

[1] HTML 5 Audio tag

www.w3school.com.cn/html5/html5…

[2] HTML DOM Audio object

www.w3school.com.cn/jsref/dom_o…

[3] HTML5 Audio

www.runoob.com/html/html5-…

[4] Audio Sprite

Jsfiddle.net/aarongloege…

[5] audioCreate.js

Github.com/jdf2e/audio…