简体   繁体   中英

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?

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM