Sound in JavaScript
January 24, 2010
I had a need to play some .mp3s when certain events happened in a web page. I managed to achieve this with an excellent open source project called Sound Manager 2.
This project embeds a flash movie in the page (with no visual component) and uses that to play the sounds.
Example
First embed the javascript required:
<script src="/site_media/soundmanager/soundmanager2.js"></script>
Here's some example setup code:
var snare = null; var bassdrum = null; soundManager.url = '/site_media/soundmanager/soundmanager2.swf'; soundManager.debugMode = false; soundManager.onload = function() { snare = soundManager.createSound({ id : 'snare', url: '/site_media/sounds/snare.mp3', volume: 50 }); bassdrum = soundManager.createSound({ id : 'bassdrum', url: '/site_media/sounds/bassdrum.mp3', volume: 50 }); }
Once this code is done, then to play a sound simply call the play() method, ie:
snare.play();