michaelmeyer
michaelmeyer

Reputation: 8215

Play a sound each time a button is clicked

I've struggled some time to find a working way of playing a sound when a linked is clicked on, and finally came up with the following:

<audio id="sound0" src="/sounds/foo">

<a href="javascript:play('sound0');">Click here</a> 

<script>function play(sound_id) {
    document.getElementById(sound_id).play();
}</script>

Now, this works fine, but only the first time the link is clicked on; after that, clicking again on it doesn't have any effect.

How can I fix this?

Upvotes: 0

Views: 176

Answers (2)

michaelmeyer
michaelmeyer

Reputation: 8215

I finally fixed this up thanks to the link @MickyScion posted in the comment. The fix is to not use the <audio> tag:

<a href="javascript:play('/sounds/foo');">Click here</a> 

<script>function play(path) {
    var sound = new Audio(path);
    sound.play();
}</script>

Rewinding the source seems to be necessary.

Upvotes: 0

RichardB
RichardB

Reputation: 2771

Think you just need to rewind the sound. Try...

 document.getElementById(sound_id).currentTime=0; 
 document.getElementById(sound_id).play();

Upvotes: 1

Related Questions