Search code examples
javascriptaudiomp3

javascript stop audio from button click


When the function generate is called, the sound should be played. If button is triggered sound sound should be stopped. What's the best way to do this?

    <script>

    var audio = new Audio('assets/spin.mp3');

        function generate()
            {

                /* some code goes here*/
                audio.play();
            }

    </script>

    <button onClick="game.rotationAngle=0; game.draw();generate();audio.stop();">start</button>

It's a kind of reset I need to perform when the button is triggered. That's why the sound needs to be stopped, before it will run again.

I get this error in debug: error


Solution

    1. You should differentiate between clicking nth and (n+1)th time. To do this, just check if the audio is paused or not.
    2. Using audio isn't valid outside the <script> tag, since you define it in the script tags.
    3. You should also set the current time to zero if you want to start the track over.

    Below is the resulting code.

    <script>
        var audio = new Audio('assets/spin.mp3');
        function generate() {
            /* some code goes here*/
            if(audio.paused) {audio.currentTime=0;audio.play()}
                       else  audio.pause();
        }
    </script>
    <button onClick="game.rotationAngle=0; game.draw();generate();">start</button>