craftyjs.github.com

Crafty.audio

Add sound files and play them. Chooses best format for browser support. Due to the nature of HTML5 audio, three types of audio files will be required for cross-browser capabilities. These formats are MP3, Ogg and WAV. When sound was not muted on before pause, sound will be unmuted after unpause. When sound is muted Crafty.pause() does not have any effect on sound.

Back to top

Crafty.audio.add

public this Crafty.audio.add(String id, String url)

id
A string to refer to sounds
url
A string pointing to the sound file

public this Crafty.audio.add(String id, Array urls)

urls
Array of urls pointing to different format of the same sound, selecting the first that is playable

public this Crafty.audio.add(Object map)

map
key-value pairs where the key is the id and the value is either a url or urls

Loads a sound to be played. Due to the nature of HTML5 audio, three types of audio files will be required for cross-browser capabilities. These formats are MP3, Ogg and WAV.

Passing an array of URLs will determine which format the browser can play and select it over any other.

Accepts an object where the key is the audio name and either a URL or an Array of URLs (to determine which type to use).

The ID you use will be how you refer to that sound when using Crafty.audio.play.

Example

//adding audio from an object
Crafty.audio.add({
shoot: ["sounds/shoot.wav",
"sounds/shoot.mp3",
"sounds/shoot.ogg"],

coin: "sounds/coin.mp3"
});

//adding a single sound
Crafty.audio.add("walk", [
"sounds/walk.mp3",
"sounds/walk.ogg",
"sounds/walk.wav"
]);

//only one format
Crafty.audio.add("jump", "sounds/jump.mp3");
Back to top

Crafty.audio.play

public this Crafty.audio.play(String id)

public this Crafty.audio.play(String id, Number repeatCount)

public this Crafty.audio.play(String id, Number repeatCount,Number volume)

id
A string to refer to sounds
repeatCount
Repeat count for the file, where -1 stands for repeat forever.
volume
volume can be a number between 0.0 and 1.0

Will play a sound previously added by using the ID that was used in Crafty.audio.add. Has a default maximum of 5 channels so that the same sound can play simultaneously unless all of the channels are playing.

Note that the implementation of HTML5 Audio is buggy at best.

Example

Crafty.audio.play("walk");

//play and repeat forever
Crafty.audio.play("backgroundMusic", -1);
Crafty.audio.play("explosion",1,0.5); //play sound once with volume of 50%
Back to top

Crafty.audio.remove

public this Crafty.audio.remove([String id])

id
A string to refer to sounds

Will stop the sound and remove all references to the audio object allowing the browser to free the memory. If no id is given, all sounds will be removed.

Example

Crafty.audio.remove("walk");