peke_peke
peke_peke

Reputation: 551

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

Upvotes: 0

Views: 3896

Answers (4)

nicael
nicael

Reputation: 19024

  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>

Upvotes: 3

Use audio.pause() instead of audio.stop()

Upvotes: 0

Angel Politis
Angel Politis

Reputation: 11313

There is no such function as audio.stop(). You can use the following instead:

function generate() {
    if(!audio.paused) { /* Check if it's not paused */
        audio.pause();  /* To pause the audio */
        audio.currentTime = 0;  /* To reset the time back to 0 */
    }
    else {
        audio.play();  /* To make it play again */
    }
};

Upvotes: 0

Azamantes
Azamantes

Reputation: 1461

You might want to use audio.pause() instead since there is no stop method. If you check Audio.prototype.stop it's undefined.

Upvotes: 2

Related Questions