Now many mobile side requires that audio playback must be triggered by the user's event, otherwise hijacked. In practice, JS network requests often appear to determine what audio to play by returning the result, which is not allowed on the mobile side.
When the move needs to play the audio through a network request callback, you have to do a bit of prep work, the code is as follows:
Loading ready to process
/** * Cyclic processing * @param {Object} data * @param {function} callback * @returns {undefined} */ function each (Data, callback) { if (typeof data === ' object ') { if (data.length) { for (var key = 0; key < data.length; key++) { if (Callback (Key, data[key]) === false) { break; } } } else { for (var key in data) { if (Callback (Key, data[key]) === false) { break; } } } } } /** * Play Audio * @param {string} name * @ param {bool} isprepare * @returns {undefined} */ function audiopaly (Name, isprepare) { each (Name.split (/\s+/), function (_, name) { if (Audiopaly.lists[name]) { if (Isprepare) { Audiopaly.lists[name].prepare (); } else { audiopaly.lists[name].play (); } } }); } audioPaly.lists = {}; /** * loading audio * @param {String} path * @param {Function} callback * @returns {undefined } */&nbSp; function loadaudio (PATH) { var audio = create (' Audio ', {preload: ' Load '}); each ({' Ogg ': ' ogg ', ' mp3 ': ' mpeg ', ' wav ': ' wav '}, function ( Name, type) { Audio.appendchild (Create (' source ', {src: '/audio/' + path + '. ') + name, type: ' audio/' + type}); }); audio.addeventlistener (' Loadedmetadata ', function () { audiopaly.lists [path] = { play: function () {//play audio.muted = false;//off Mute audio.play (); }, prepare: function () {//Preparation audio.muted = true;//Mute, some mobile side does not set this will play directly audio.play (); audio.pause (); } }; }); Document.body.appendChild (audio); } // Load Audio loadaudio (' Test ');
User Event triggering processing
The bind user can trigger the element click event Element.addeventlistener (' click ', Function () {audiopaly (' Test '), true);//audio trigger for callback to play again//Network Request code: .. Network callback function () {audiopaly (' test ');//Play processing} .....});
Prepare the audio file (why not more to say, specifically see the terminal support audio format to be determined)
/audio/test.mp3
/audio/test.ogg
/audio/test.wav
This code is not complicated, just takes advantage of a little license in the mobile limit, when played in the user trigger event, then the subsequent operation can be played again.
As long as we play the audio after the user triggers and pause or mute in time can not be heard audio, and then in the network request callback operation again play can be achieved, dynamic playback.
Mobile Audio playback compatibility scheme