javascriptaudio

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


Solution

  • 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