HTML5 audio start over

19,776

Solution 1

You can try this code:

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

It looks like this is the simplest solution.

Solution 2

This is the code I've been using and it's working for me:

            if(audioSupport.duration > 0 && !audioSupport.paused){

                //already playing
                audioSupport.pause();
                audioSupport.currentTime = 0;
                audioSupport.play();

            }else{

                //not playing

                audioSupport.play();    

            }

Solution 3

I noticed that on Firefox, playing a sound again and again really fast (like a short ticking sound) will skip beats often. The best solution I got was to simply call cloneNode and play each sound that way. Its not perfect (compared to Chrome where it sounds flawless):

var audio = document.getElementById('myaudio');
setInterval(function() {
    audio.cloneNode().play();
}, 100);
Share:
19,776

Related videos on Youtube

Ωmega
Author by

Ωmega

Updated on September 15, 2022

Comments

  • Ωmega
    Ωmega over 1 year

    Having

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

    I play the click sound when needed by

    audio.play()
    

    However, sometimes user is so fast that a browser does not play the audio at all (probably when still playing a previous play request). Is this issue related to preload?

    How can I force a browser to stop playing and start over? There is no stop, just pause in HTML5 audio component, correct? What workaround can be used here?


    Update - Additional note:

    I have multiple checkbox-like div elements with a touchend event. When such event is triggered, the elements visually change, a sound is played and an internal variable is set accordingly. If user tap on these elements slowly, everything works nicely. If tap fast, the sound is often completely skipped...

  • fdrv
    fdrv over 8 years
    Great solution. Faster then excepted answer. Ty
  • Isaac Lyman
    Isaac Lyman over 5 years
    @MaciejBukowski Chrome 71.