I want to add a short audio track to a game of concentration I'm coding. I want the sound to occur when the user has won the game. How do I go about doing this? I would really appreciate the help, thank you.
-
2\$\begingroup\$ This might help: stackoverflow.com/questions/1933969/… \$\endgroup\$– bummzackOct 25, 2011 at 7:30
-
\$\begingroup\$ In my game, I play music with an embedded Youtube player. \$\endgroup\$– jcoraDec 28, 2011 at 13:55
-
\$\begingroup\$ What browsers and versions do You want to support? \$\endgroup\$– MichasDec 28, 2011 at 14:36
4 Answers
If you're using something like canvas and you're already depending on the browser supporting HTML5, you can use the audio
element.
var win = new Audio('srcfile.wav');
if(playerWon === true){
win.play();
}
Audio in HTML5 is a minefield at the moment, with patchy format support.
We wrote a few blog posts about audio support in HTML5. This chart shows browser support: http://www.scirra.com/blog/44/on-html5-audio-formats-aac-and-ogg#chart
Surprisingly, IE doesn't support playback of WAVs. You should pick audio 2 formats to get coverage on all the platforms.
Beware using MP3's in games
It will cost you $2,500 per title in licensing fees if it has more than 5,000 distributions. http://www.scirra.com/blog/64/why-you-shouldnt-use-mp3-in-your-html5-games
We think the best combination to use is AAC/Ogg to cover all browsers.
I found an article describing this library which should fit your needs.
If you don't have sound files yet and want to create them with some fx library then you might want to look at jsfx which I used in my last game typdown (specially these two files are interesting (don't mind the coffeescript, it all compiles to javascript): sounds and game controller
The Web Audio API is perfect for playing audio in javascript, but currently only Chrome supports it.