5

I am currently making a game in Javascript but when trying to shoot, the shooting sound doesn't restart. My HTML looks like this:

<embed id="playerShot" src="resources/sounds/ump45shot.mp3" hidden="true" autostart="false"loop="false" volume="20">

My Javascript function is

function shoot() {
document.getElementById("playerShot").Play();
}

Is there any way to restart the sound before playing it again?

  • I'd personally keep a clone of that element in the memory, then append a clone of it to the document when necessary and remove it after it's finished playing. That's what I do with the HTML5 `audio` element and jQuery, not sure how you'd apply that to an `embed` with pure JS. – Fabrício Matté Nov 12 '12 at 01:12

3 Answers3

1

If you are making a game in JavaScript, I'd suggest choosing JavaScript to HTML to load and manipulate your resources, like sounds and graphics. You can read this article to get started with Web Audio API: http://www.html5rocks.com/en/tutorials/webaudio/intro/ .

0

I'd recommend you use the <audio> element, in my opinion it's more suited to your needs than the embed tag. https://developer.mozilla.org/en-US/docs/HTML/Element/Audio

To rewind an <audio> tag: document.getElementById('iamanaudioelement').currentTime = 0

(side note: not all browsers support mp3 <audio> elements. If you intend for Firefox users to play your game, you should feature detect whether a browser supports has MP3 support, eg with Modernizr, and create ogg or mp3 audio tags as appropriate.)

S M
  • 8,155
  • 3
  • 35
  • 36
0

Is this what you're looking for?

<button onclick="playSfx('resources/sounds/ump45shot.mp3');">PLAY</button>

<!--Script-->

<script>
    function playSfx(filename){
    var snd = new Audio(filename);
    snd.play();
}

</script>
William
  • 4,422
  • 17
  • 55
  • 108