简体   繁体   中英

Stop audio after X seconds in js

I do a little car game in 3D. For example, I want when the player, press up to speed, he has the sound start at first and after speed. But the start only one time and speed in a loop. My HTML:

<audio preload="auto" id="start"><source src="sounds/start.mp3" type="audio/mp3"></audio>
<audio preload="auto" id="speed"><source src="sounds/speed.mp3" type="audio/mp3"></audio>

I have tried this thing in JS, but did not work:

document.getElementById('start').play();
setTimeout(document.getElementById('speed').play(),2000);
setTimeout(document.getElementById('start').pause(),2000);

How can I do ? Thanks

You need to wrap your calls in an anonymous function so that they aren't immediately invoked, for example:

var player = document.getElementById('player');
setTimeout(function(){
    player.play();

    setTimeout(function(){
        player.pause();
        player.currentTime = 0;
    }, 2000);
}, 1000);

Fiddle: http://jsfiddle.net/fyfRd/

To stop the file, you need to pause and reset the currentTime to 0

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