2

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

Suman Bogati
  • 6,289
  • 1
  • 23
  • 34
user3414480
  • 115
  • 1
  • 2
  • 7

1 Answers1

5

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

Rob M.
  • 35,491
  • 6
  • 51
  • 50
  • @Vineet I'm not sure, it's possible the mobile browser doesn't support the `pause` method or the `currentTime` property. I would check something like [caniuse](https://caniuse.com/#feat=audio-api) – Rob M. Aug 21 '17 at 17:05
  • @RobM. Should I go with this API ? – Vineet Aug 21 '17 at 17:09