Recently MADE two small games, design to audio playback. The problems encountered and liberation methods are recorded as follows:
1. Audio playback delay
(Audio. Volume =0) (audio. Volume =0) (audio. Volume =0Copy the code
2. Loop the audio
Initial code: <audio id="myAudio" loop="true"> <source src="path/music/audio.mp3" type="audio/mpeg"> <source src="path/music/audio.ogg" type="audio/ogg"> </audio>Copy the code
Chorme, no problem, superb repeat playback
Open it in the browser (Mozilla kernel) of the Oppo phone, cry ~~~ play it once, and never play it again
In the middle of the test listening onend event, in my own phone did not listen successfully
myAudio.addEventListener('ended', function() {
this.currentTime = 0;
this.play();
}, false);
Copy the code
Final solution:
The onUpdateTime event that listens for audio when the audio length is reduced and the current playback progress is less than the error time.
Let errorTime = 0.2; MyAudio. AddEventListener (" timeUpdate ", function() { if (this.duration - this.currentTime <= errorTime) { this.currentTime = 0; this.play(); }});Copy the code
3. Set the time when the audio starts to play
Background: To reduce requests, multiple small audio files are merged into one audio file. When a scene audio file needs to be played, specify the start and end time of playback. The opPO browser (Mozilla kernel) directly sets the currentTime property to specify the start time of playback. The Mozilla kernel needs currentTime to be valid while the audio is playing
Core code: Let audioArr = {eat:{startTime:0, endTime:1, errorTime:0.02// errorTime}, drink:{startTime:1.2, endTime:2.2, ErrorTime :0.02}, sleep:{startTime:3, endTime:4, errorTime:0.02}} // Listen to audio playback progress myAudio. If (myAudio. CurrentTime >= typeobj.endTime-typeobj.errorTime) {myAudio. Pause (); }}); function playRangeAudio(typeObj){ if (myAudio.currentTime > 0) { myAudio.currentTime = typeObj.startTime; myAudio.play(); } // playRangeAudio(audioarr.eat);Copy the code