Search code examples
javascripthtmlaudioplaybackrestart

Create multiple <audio> elements to prevent a cut of


If I trigger an HTML5 element via a button, to make it play, I have the problem that, when I hit the button again, the sample will not be played again (since it's already playing).

If I use: n.pause() n.currentTime = 0 n.play()

it will be cut of which is also not very nice.

Is there an easy way (I'm kind of a beginner) to create a new audio element and destroy it after it has ended, or even another possibility I might can't think of atm?


Solution

  • I would suggest removing any existing audio elements from your HTML so you can just use Javascript.

    Eachtime a user clicks your button

    <button onclick="playSound();">click me</button>
    

    a new instance of Audio object is created.

    function playSound() {
        var n = new Audio("example.mp3");
        n.play();
    }