2

Possible Duplicate:
Playing sound notifications using Javascript?

I'm making a game in JS, and I need a proper way to play a sound when something happens. How do you do that with JS/HTML5? I saw this article, but even with their example, it doesn't really work! Sometimes I do hear that bird, but only for a short time, and I can't get it to work anymore then.

Community
  • 1
  • 1
corazza
  • 31,222
  • 37
  • 115
  • 186

2 Answers2

9

HTML5 has the new <audio>-Tag that can be used to play sound. It even has a pretty simple JavaScript Interface:

<audio id="sound1" src="yoursound.mp3" preload="auto"></audio>
<button onclick="document.getElementById('sound1').play();">Play it</button>
klaustopher
  • 6,702
  • 1
  • 22
  • 25
5

You can make use of the HTML5 <audio> tag: http://jsfiddle.net/STTnr/.

var audio = document.getElementById('audio');

setTimeout(function() {
    audio.play();        // play it through JavaScript after 3 seconds
}, 3000);

HTML:

<audio src="something" id="audio"></audio>

Just hide the element itself:

#audio {
    display: none;
}

Do note that no browser supports all formats. This can be frustrating, but you can supply your audio in several formats.

pimvdb
  • 151,816
  • 78
  • 307
  • 352
  • Thank you very much, but may I ask why can't the sound be played multiple times? – corazza Oct 01 '11 at 15:15
  • 1
    @bane: If you mean looping, try adding a `loop` attribute like ` – pimvdb Oct 01 '11 at 15:18
  • No, not that, I need the sound to be played when the player does something, but it gets played only the first time! – corazza Oct 01 '11 at 15:20
  • 1
    @bane: Oh I see. Well you can put the seeker at the beginning and play again: http://jsfiddle.net/STTnr/2/. – pimvdb Oct 01 '11 at 15:23
  • I did that, and it's acting funny. It doesn't work with my local sound (.wav), but when I use the wikipedia example - it does! Maybe it is something with the file format... – corazza Oct 01 '11 at 15:29
  • 1
    @bane: Perhaps you're using Google Chrome, in which `.wav` is not supported (look at the article I posted a link to). – pimvdb Oct 02 '11 at 11:38
  • Oh! Thank you very much, again! Although, ".wav" seems to be not unsupported, but half-supported... I'll both ".wav" and ".mp3", so it will, hopefully, work for everyone. – corazza Oct 02 '11 at 11:50