Search code examples
javascripthtmlhtml5-audio

Audiotag time control (#t=5,6) not working second time


From this answer, To begin playing an audio at a certain time, we can use #t=begintime,endtime after the link.

This is working for me but only the first time.The second time, the audio is playing but not in the specified time.

Like this:

 function drainwater(){
       document.getElementById("drain").play();
     } 
<audio src="https://upload.wikimedia.org/wikipedia/commons/b/b9/Kitchen_sink_draining_water.ogg#t=5,6" id="drain"></audio>   
   


<button onclick='drainwater()'> Drain </button>

The second time, the audio is playing longer than I expected. What is the problem? How can I overcome this?


As a workaround, I tried using a timer and pausing the audio after a certain time.

Like this:

function drainwater(){
       document.getElementById("drain").play();
     }
     
     
 function pause(){
       document.getElementById("drain").pause();
     }
<audio src="https://upload.wikimedia.org/wikipedia/commons/b/b9/Kitchen_sink_draining_water.ogg" id="drain"></audio>   
   


<button onclick='drainwater();setTimeout(pause, 2000)'> Drain </button>

(An advice for those who may be using this solution: Don't forget to remove the #t=5,6 from the link or this will not work.)

This maybe enough for homogenous audios like that of 2 minutes of raining audio- there is no difference between the first 10 seconds and the second 10 seconds- so we can use this method to play it for a specified amount of time.

But for general audios , this does not work. The second time the button is clicked, the audio is not starting from the specified position.

So Why is this happening? What can we do to play the audio at the specific time again and again on button click?


Solution

  • It looks like at least Chrome and Firefox need the URL to be set again in order to do what you want. If you change your drainwater() function like this it should work.

    function drainwater(){
        const $drain = document.getElementById("drain");
    
        $drain.onpause = () => $drain.src = $drain.src;
        $drain.play();
    }
    

    I'm not sure though if this is a bug or the intended behavior.