Brit Ann
Brit Ann

Reputation: 3

Adding OnClick Stop to Audio

I made this image so when you click on it, audio begins to play. But, because I'm using a full song and not just a little sound, I need to also be able to stop it.

How can I make it so I can toggle on and off the sound?

<audio id="1st_sound">
    <source src="http://k007.kiwi6.com/hotlink/nbgq3cyywi/Damn_Good_Wife.mp3"     type="audio/mpeg" />
</audio>


<img src="http://static.tumblr.com/6s0fefr/t3wne2irz/damngoodwifeplaybutton.jpg"     onClick="document.getElementById('1st_sound').play(); return false;" />

Upvotes: 0

Views: 963

Answers (1)

Forte Roumi
Forte Roumi

Reputation: 41

You can use this function to check if the audio is playing:

function isPlaying(playerId) {
    var player = document.getElementById(playerId);
    return !player.paused && !player.ended && 0 < player.currentTime;
}

You could use this in a if statement.

if (isPlaying(...)) {..Pause..} else {..Play..}

For muting the sound you can use this: Muting a HTML5 audio element using a custom button

if(document.getElementById('background_audio').muted) {
    document.getElementById('background_audio').muted = true;
} else {
    document.getElementById('background_audio').muted = false;
}

Upvotes: 1

Related Questions