HTML5 audio start

Having

var audio = new Audio("click.ogg") 

I play a click sound if necessary

 audio.play() 

However, sometimes the user works so fast that the browser does not play sound at all (possibly when playing the previous play request). Is this problem related to preload ?

How to make the browser stop playing and start? No stop , only pause in the HTML5 audio component, right? What workaround can I use here?


Update - additional note:

I have several elements marked with a div flag with a touchend event. When such an event is triggered, the elements visually change, the sound is played, and the internal variable is set accordingly. If the user clicks on these items slowly, everything works well. When pressed quickly, the sound is often completely skipped ...

+4
source share
3 answers

You can try the following:

 audio.currentTime = 0; audio.play(); 

It works well for me

+16
source

This is the code I used and it works for me:

  if(audioSupport.duration > 0 && !audioSupport.paused){ //already playing audioSupport.pause(); audioSupport.currentTime = 0; audioSupport.play(); }else{ //not playing audioSupport.play(); } 
+7
source

The only way I found how to quickly play a short sound (so fast that the second sound starts to the first ends) is to actually load 5 or 10, and if you need to play again, but they are already playing, to the next one that doesn't reproduced:

  var soundEls = [];//load 10 audios instead of 1 for(var i=0;i<10;i++){ var soundEl = document.createElement('audio'); soundEl.src = url; soundEl.preload = 'auto'; $(this._soundEl).append(soundEl); soundEls.push(soundEl); } var soundElIndex = 0; return {play:function(){ var soundEl = soundEls[soundElIndex]; if(soundEl.duration > 0 && !soundEl.paused){ //already playing, switch to next soundEl soundElIndex++; if(!soundEls[soundElIndex]) soundElIndex=0; soundEls[soundElIndex].play(); }else{ //not playing soundEl.play(); } }}; 

As a result, you can play the same sound above you.

Perhaps this is not the right way to do this.

0
source

Source: https://habr.com/ru/post/1441164/


All Articles