SoundManager 2 Basic Examples

Wondering where to start? The following are some simple examples showing how to get started with SoundManager 2.

Keep in mind these methods will not be available until soundManager.onload() fires. The initialization time for SM2 seems to vary across browsers/platforms, so this method is called with a delay after window.onload() to be safe.

eg.

soundManager.onload = function() {
  // soundManager is ready to use - createSound() / play() etc. can now be called
}

Demo 1a: Create + play (shortcut method)

soundManager.play('mySound0','../mpc/audio/AMB_SN_5.mp3');

Creates and plays a sound with ID "mySound0", at the specified URL. The sound can then be referenced by that ID later, eg. soundManager.play('mySound0');

Note that this method is only provided for convenience, and allows only ID and URL as parameters. If you want to specify other options (volume, loop, event handlers), you must use the object literal syntax as given below.

Demo 1b: Create + play (recommended method)

soundManager.createSound({
 id:'mySound1',
 url:'../mpc/audio/CHINA_1.mp3'
});
soundManager.play('mySound1');

Creates, then plays a sound. This object literal method allows for other parameters to be used (see demo 2)

Demo 2: Create with onfinish event handler + play with volume argument

soundManager.createSound({
 id:'mySound1',
 url:'../mpc/audio/CHINA_1.mp3',
 onfinish:function() {
   alert(this.sID+' finished playing');
 }
});
soundManager.play('mySound1',{volume:50});

(creates, then plays a new sound - a function is called when the sound finishes playing)

Demo 3: Play a pre-existing sound

soundManager.play('aDrumSound');

This plays an existing sound which was created by soundManager.onload() (for reference, view source of this page.)

Demo 4a: Play a sequence of sounds via "onfinish"

soundManager.play('aDrumSound',{onfinish:function(){soundManager.play('aCymbalSound');}})

Differently formatted:

soundManager.play(
 'aDrumSound',
 {
  onfinish:function() {
    soundManager.play('aCymbalSound');
  }
 }
);

This will play an existing sound (created in-page), and uses the "onfinish" handler to make a call to play a second, pre-existing sound.

Bug note: Running this demo will change the way "aDrumSound" plays in Demo 3 as an onfinish handler is set here (ie., running demo 3 will also include the "aSymbalSound" sound after running this one.) When set via .play(), this behaviour should only apply to this .play() instance, but does not currently.

Demo 4b: Create and play a sequence of new sounds via "onfinish"

soundManager.createSound({
 id:'aRimSound',
 url:'../mpc/audio/AMB_RIM1.mp3',
 onfinish:function() {
   soundManager.play('aBassDrum','AMB_BD_1.mp3');
 }
});
soundManager.play('aRimSound');

This will crate and play a new sound, using the "onfinish" handler to create and play a second, new sound.

It is recommended to create sound objects first, to simplify troubleshooting.

SoundManager 2 Demos