API Documentation for: 0.6.2
Show:

Sound Class

Defined in: Sound:82
Module: SoundJS

The Sound class is the public API for creating sounds, controlling the overall sound levels, and managing plugins. All Sound APIs on this class are static.

Registering and Preloading
Before you can play a sound, it must be registered. You can do this with registerSound, or register multiple sounds using registerSounds. If you don't register a sound prior to attempting to play it using play or create it using createInstance, the sound source will be automatically registered but playback will fail as the source will not be ready. If you use PreloadJS, registration is handled for you when the sound is preloaded. It is recommended to preload sounds either internally using the register functions or externally using PreloadJS so they are ready when you want to use them.

Playback
To play a sound once it's been registered and preloaded, use the play method. This method returns a AbstractSoundInstance which can be paused, resumed, muted, etc. Please see the AbstractSoundInstance documentation for more on the instance control APIs.

Plugins
By default, the WebAudioPlugin or the HTMLAudioPlugin are used (when available), although developers can change plugin priority or add new plugins (such as the provided FlashAudioPlugin). Please see the Sound API methods for more on the playback and plugin APIs. To install plugins, or specify a different plugin order, see Sound/installPlugins.

Example

 createjs.FlashAudioPlugin.swfPath = "../src/soundjs/flashaudio";
 createjs.Sound.registerPlugins([createjs.WebAudioPlugin, createjs.FlashAudioPlugin]);
 createjs.Sound.alternateExtensions = ["mp3"];
 createjs.Sound.on("fileload", this.loadHandler, this);
 createjs.Sound.registerSound("path/to/mySound.ogg", "sound");
 function loadHandler(event) {
     // This is fired for each sound that is registered.
     var instance = createjs.Sound.play("sound");  // play using id.  Could also use full source path or event.src.
     instance.on("complete", this.handleComplete, this);
     instance.volume = 0.5;
 }

The maximum number of concurrently playing instances of the same sound can be specified in the "data" argument of registerSound. Note that if not specified, the active plugin will apply a default limit. Currently HTMLAudioPlugin sets a default limit of 2, while WebAudioPlugin and FlashAudioPlugin set a default limit of 100.

 createjs.Sound.registerSound("sound.mp3", "soundId", 4);

Sound can be used as a plugin with PreloadJS to help preload audio properly. Audio preloaded with PreloadJS is automatically registered with the Sound class. When audio is not preloaded, Sound will do an automatic internal load. As a result, it may fail to play the first time play is called if the audio is not finished loading. Use the fileload event to determine when a sound has finished internally preloading. It is recommended that all audio is preloaded before it is played.

 var queue = new createjs.LoadQueue();
    queue.installPlugin(createjs.Sound);

Audio Sprites
SoundJS has added support for AudioSprite, available as of version 0.6.0. For those unfamiliar with audio sprites, they are much like CSS sprites or sprite sheets: multiple audio assets grouped into a single file.

Example

    var assetsPath = "./assets/";
    var sounds = [{
        src:"MyAudioSprite.ogg", data: {
            audioSprite: [
                {id:"sound1", startTime:0, duration:500},
                {id:"sound2", startTime:1000, duration:400},
                {id:"sound3", startTime:1700, duration: 1000}
            ]}
        }
    ];
    createjs.Sound.alternateExtensions = ["mp3"];
    createjs.Sound.on("fileload", loadSound);
    createjs.Sound.registerSounds(sounds, assetsPath);
    // after load is complete
    createjs.Sound.play("sound2");

Mobile Playback
Devices running iOS require the WebAudio context to be "unlocked" by playing at least one sound inside of a user- initiated event (such as touch/click). Earlier versions of SoundJS included a "MobileSafe" sample, but this is no longer necessary as of SoundJS 0.6.2.

  • In SoundJS 0.4.1 and above, you can either initialize plugins or use the playEmptySound method in the call stack of a user input event to manually unlock the audio context.
  • In SoundJS 0.6.2 and above, SoundJS will automatically listen for the first document-level "mousedown" and "touchend" event, and unlock WebAudio. This will continue to check these events until the WebAudio context becomes "unlocked" (changes from "suspended" to "running")
  • Both the "mousedown" and "touchend" events can be used to unlock audio in iOS9+, the "touchstart" event will work in iOS8 and below. The "touchend" event will only work in iOS9 when the gesture is interpreted as a "click", so if the user long-presses the button, it will no longer work.
  • When using the EaselJS Touch class, the "mousedown" event will not fire when a canvas is clicked, since MouseEvents are prevented, to ensure only touch events fire. To get around this, you can either rely on "touchend", or:
    1. Set the allowDefault property on the Touch class constructor to true (defaults to false).
    2. Set the preventSelection property on the EaselJS Stage to false.
    These settings may change how your application behaves, and are not recommended.

Loading Alternate Paths and Extension-less Files
SoundJS supports loading alternate paths and extension-less files by passing an object instead of a string for the src property, which is a hash using the format {extension:"path", extension2:"path2"}. These labels are how SoundJS determines if the browser will support the sound. This also enables multiple formats to live in different folders, or on CDNs, which often has completely different filenames for each file.

Priority is determined by the property order (first property is tried first). This is supported by both internal loading and loading with PreloadJS.

Note: an id is required for playback.

Example

    var sounds = {path:"./audioPath/",
            manifest: [
            {id: "cool", src: {mp3:"mp3/awesome.mp3", ogg:"noExtensionOggFile"}}
    ]};

    createjs.Sound.alternateExtensions = ["mp3"];
    createjs.Sound.addEventListener("fileload", handleLoad);
    createjs.Sound.registerSounds(sounds);

Known Browser and OS issues

IE 9 HTML Audio limitations

  • There is a delay in applying volume changes to tags that occurs once playback is started. So if you have muted all sounds, they will all play during this delay until the mute applies internally. This happens regardless of when or how you apply the volume change, as the tag seems to need to play to apply it.
  • MP3 encoding will not always work for audio tags, particularly in Internet Explorer. We've found default encoding with 64kbps works.
  • Occasionally very short samples will get cut off.
  • There is a limit to how many audio tags you can load and play at once, which appears to be determined by hardware and browser settings. See HTMLAudioPlugin.MAX_INSTANCES for a safe estimate.

Firefox 25 Web Audio limitations

  • mp3 audio files do not load properly on all windows machines, reported here.
    For this reason it is recommended to pass another FF supported type (ie ogg) first until this bug is resolved, if possible.

Safari limitations

  • Safari requires Quicktime to be installed for audio playback.

iOS 6 Web Audio limitations

  • Sound is initially locked, and must be unlocked via a user-initiated event. Please see the section on Mobile Playback above.
  • A bug exists that will distort un-cached web audio when a video element is present in the DOM that has audio at a different sampleRate.

Android HTML Audio limitations

  • We have no control over audio volume. Only the user can set volume on their device.
  • We can only play audio inside a user event (touch/click). This currently means you cannot loop sound or use a delay.

Web Audio and PreloadJS

  • Web Audio must be loaded through XHR, therefore when used with PreloadJS, tag loading is not possible. This means that tag loading can not be used to avoid cross domain issues.

Methods

_beginPlaying

(
  • instance
  • playProps
)
Boolean protected static

Defined in _beginPlaying:1510

Begin playback. This is called immediately or after delay by Sound/playInstance.

Parameters:

Returns:

Boolean:

If the sound can start playing. If there are no available channels, or the instance fails to start, this will return false.

_dispatchEvent

(
  • eventObj
  • eventPhase
)
protected

Parameters:

_getSrcById

(
  • value
)
String protected static

Defined in _getSrcById:1533

Get the source of a sound via the ID passed in with a register call. If no ID is found the value is returned instead.

Parameters:

  • value String

    The ID the sound was registered with.

Returns:

String:

The source of the sound if it has been registered with this ID or the value that was passed in.

_handleLoadComplete

(
  • event
)
protected static

Defined in _handleLoadComplete:679

Available since 0.6.0

Used to dispatch fileload events from internal loading.

Parameters:

  • event Object

    A loader event.

_parsePath

(
  • value
)
Object protected static

Defined in _parsePath:1177

Parse the path of a sound. Alternate extensions will be attempted in order if the current extension is not supported

Parameters:

  • value String

    The path to an audio source.

Returns:

Object:

A formatted object that can be registered with the activePlugin and returned to a preloader like PreloadJS.

_parseSrc

(
  • value
)
Object protected static

Defined in _parseSrc:1207

Parse the path of a sound based on properties of src matching with supported extensions. Returns false if none of the properties are supported

Parameters:

  • value Object

    The paths to an audio source, indexed by extension type.

Returns:

Object:

A formatted object that can be registered with the activePlugin and returned to a preloader like PreloadJS.

_playFinished

(
  • instance
)
protected static

Defined in _playFinished:1546

A sound has completed playback, been interrupted, failed, or been stopped. This method removes the instance from Sound management. It will be added again, if the sound re-plays. Note that this method is called from the instances themselves.

Parameters:

_playInstance

(
  • instance
  • playProps
)
Boolean protected static

Defined in _playInstance:1473

Play an instance. This is called by the static API, as well as from plugins. This allows the core class to control delays.

Parameters:

Returns:

Boolean:

If the sound can start playing. Sounds that fail immediately will return false. Sounds that have a delay will return true, but may still fail to play.

_registerPlugin

(
  • plugin
)
Boolean private static

Defined in _registerPlugin:734

Used by registerPlugins to register a Sound plugin.

Parameters:

  • plugin Object

    The plugin class to install.

Returns:

Boolean:

Whether the plugin was successfully initialized.

_registerSound

(
  • src
)
Object private static

Defined in _registerSound:856

Available since 0.6.0

Internal method for loading sounds. This should not be called directly.

Parameters:

  • src Object

    The object to load, containing src property and optionally containing id and data.

Returns:

Object:

An object with the modified values that were passed in, which defines the sound. Returns false if the source cannot be parsed or no plugins can be initialized. Returns true if the source is already loaded.

addEventListener

(
  • type
  • listener
  • [useCapture]
)
Function | Object

Adds the specified event listener. Note that adding multiple listeners to the same function will result in multiple callbacks getting fired.

Example

 displayObject.addEventListener("click", handleClick);
 function handleClick(event) {
    // Click happened.
 }

Parameters:

  • type String

    The string type of the event.

  • listener Function | Object

    An object with a handleEvent method, or a function that will be called when the event is dispatched.

  • [useCapture] Boolean optional

    For events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.

Returns:

Function | Object:

Returns the listener for chaining or assignment.

createInstance

(
  • src
  • [startTime=null]
  • [duration=null]
)
AbstractSoundInstance static

Defined in createInstance:1300

Available since 0.4.0

Creates a AbstractSoundInstance using the passed in src. If the src does not have a supported extension or if there is no available plugin, a default AbstractSoundInstance will be returned that can be called safely but does nothing.

Example

 var myInstance = null;
 createjs.Sound.on("fileload", handleLoad);
 createjs.Sound.registerSound("myAudioPath/mySound.mp3", "myID", 3);
 function handleLoad(event) {
     myInstance = createjs.Sound.createInstance("myID");
     // alternately we could call the following
     myInstance = createjs.Sound.createInstance("myAudioPath/mySound.mp3");
 }

NOTE to create an audio sprite that has not already been registered, both startTime and duration need to be set. This is only when creating a new audio sprite, not when playing using the id of an already registered audio sprite.

Parameters:

  • src String

    The src or ID of the audio.

  • [startTime=null] Number optional

    To create an audio sprite (with duration), the initial offset to start playback and loop from, in milliseconds.

  • [duration=null] Number optional

    To create an audio sprite (with startTime), the amount of time to play the clip for, in milliseconds.

Returns:

AbstractSoundInstance:

A AbstractSoundInstance that can be controlled after it is created. Unsupported extensions will return the default AbstractSoundInstance.

dispatchEvent

(
  • eventObj
  • [bubbles]
  • [cancelable]
)
Boolean

Dispatches the specified event to all listeners.

Example

 // Use a string event
 this.dispatchEvent("complete");

 // Use an Event instance
 var event = new createjs.Event("progress");
 this.dispatchEvent(event);

Parameters:

  • eventObj Object | String | Event

    An object with a "type" property, or a string type. While a generic object will work, it is recommended to use a CreateJS Event instance. If a string is used, dispatchEvent will construct an Event instance if necessary with the specified type. This latter approach can be used to avoid event object instantiation for non-bubbling events that may not have any listeners.

  • [bubbles] Boolean optional

    Specifies the bubbles value when a string was passed to eventObj.

  • [cancelable] Boolean optional

    Specifies the cancelable value when a string was passed to eventObj.

Returns:

Boolean:

Returns false if preventDefault() was called on a cancelable event, true otherwise.

getCapabilities

() Object deprecated static

Defined in getCapabilities:815

Deprecated, please use capabilities instead.

Returns:

Object:

An object containing the capabilities of the active plugin.

getCapability

(
  • key
)
Number | Boolean deprecated static

Defined in getCapability:828

Deprecated, please use capabilities instead.

Parameters:

  • key String

    The capability to retrieve

Returns:

Number | Boolean:

The value of the capability.

getDefaultPlayProps

(
  • src
)
PlayPropsConfig

Defined in getDefaultPlayProps:1455

Available since 0.6.1

Get the default playback properties for the passed in src or ID. These properties are applied to all new SoundInstances. Returns null if default does not exist.

Parameters:

  • src String

    The src or ID used to register the audio.

Returns:

PlayPropsConfig:

returns an existing PlayPropsConfig or null if one does not exist

getMute

() Boolean deprecated static

Defined in getMute:1428

Available since 0.4.0

Deprecated, please use muted instead.

Returns:

Boolean:

The mute value of Sound.

getPreloadHandlers

() Object protected static

Get the preload rules to allow Sound to be used as a plugin by PreloadJS. Any load calls that have the matching type or extension will fire the callback method, and use the resulting object, which is potentially modified by Sound. This helps when determining the correct path, as well as registering the audio instance(s) with Sound. This method should not be called, except by PreloadJS.

Returns:

Object:

An object containing:

  • callback: A preload callback that is fired when a file is added to PreloadJS, which provides Sound a mechanism to modify the load parameters, select the correct file format, register the sound, etc.
  • types: A list of file types that are supported by Sound (currently supports "sound").
  • extensions: A list of file extensions that are supported by Sound (see SUPPORTED_EXTENSIONS).

getVolume

() Number deprecated static

Defined in getVolume:1393

Deprecated, please use volume instead.

Returns:

Number:

The master volume, in a range of 0-1.

hasEventListener

(
  • type
)
Boolean

Indicates whether there is at least one listener for the specified event type.

Parameters:

  • type String

    The string type of the event.

Returns:

Boolean:

Returns true if there is at least one listener for the specified event.

initialize

() deprecated protected

Inherited from EventDispatcher but overwritten in initialize:1683

REMOVED. Removed in favor of using MySuperClass_constructor. See extend and promote for details.

There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance.

initializeDefaultPlugins

() Boolean static

Defined in initializeDefaultPlugins:775

Available since 0.4.0

Initialize the default plugins. This method is automatically called when any audio is played or registered before the user has manually registered plugins, and enables Sound to work without manual plugin setup. Currently, the default plugins are WebAudioPlugin followed by HTMLAudioPlugin.

Example

if (!createjs.initializeDefaultPlugins()) { return; }

Returns:

Boolean:

True if a plugin was initialized, false otherwise.

initLoad

(
  • src
)
Object | AbstractLoader protected static

Defined in initLoad:843

Process manifest items from PreloadJS. This method is intended for usage by a plugin, and not for direct interaction.

Parameters:

  • src Object

    The object to load.

Returns:

Object | AbstractLoader:

An instance of AbstractLoader.

isReady

() Boolean static

Defined in isReady:796

Determines if Sound has been initialized, and a plugin has been activated.

Example

This example sets up a Flash fallback, but only if there is no plugin specified yet.

if (!createjs.Sound.isReady()) {
    createjs.FlashAudioPlugin.swfPath = "../src/soundjs/flashaudio/";
    createjs.Sound.registerPlugins([createjs.WebAudioPlugin, createjs.HTMLAudioPlugin, createjs.FlashAudioPlugin]);
}

Returns:

Boolean:

If Sound has initialized a plugin.

loadComplete

(
  • src
)
Boolean static

Defined in loadComplete:1148

Available since 0.4.0

Check if a source has been loaded by internal preloaders. This is necessary to ensure that sounds that are not completed preloading will not kick off a new internal preload if they are played.

Example

var mySound = "assetPath/asset0.ogg";
if(createjs.Sound.loadComplete(mySound) {
    createjs.Sound.play(mySound);
}

Parameters:

  • src String

    The src or id that is being loaded.

Returns:

Boolean:

If the src is already loaded.

off

(
  • type
  • listener
  • [useCapture]
)

Inherited from EventDispatcher: off:263

A shortcut to the removeEventListener method, with the same parameters and return value. This is a companion to the .on method.

IMPORTANT: To remove a listener added with on, you must pass in the returned wrapper function as the listener. See on for an example.

Parameters:

  • type String

    The string type of the event.

  • listener Function | Object

    The listener function or object.

  • [useCapture] Boolean optional

    For events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.

on

(
  • type
  • listener
  • [scope]
  • [once=false]
  • [data]
  • [useCapture=false]
)
Function

Inherited from EventDispatcher: on:187

A shortcut method for using addEventListener that makes it easier to specify an execution scope, have a listener only run once, associate arbitrary data with the listener, and remove the listener.

This method works by creating an anonymous wrapper function and subscribing it with addEventListener. The wrapper function is returned for use with removeEventListener (or off).

IMPORTANT: To remove a listener added with on, you must pass in the returned wrapper function as the listener, or use remove. Likewise, each time you call on a NEW wrapper function is subscribed, so multiple calls to on with the same params will create multiple listeners.

Example

    var listener = myBtn.on("click", handleClick, null, false, {count:3});
    function handleClick(evt, data) {
        data.count -= 1;
        console.log(this == myBtn); // true - scope defaults to the dispatcher
        if (data.count == 0) {
            alert("clicked 3 times!");
            myBtn.off("click", listener);
            // alternately: evt.remove();
        }
    }

Parameters:

  • type String

    The string type of the event.

  • listener Function | Object

    An object with a handleEvent method, or a function that will be called when the event is dispatched.

  • [scope] Object optional

    The scope to execute the listener in. Defaults to the dispatcher/currentTarget for function listeners, and to the listener itself for object listeners (ie. using handleEvent).

  • [once=false] Boolean optional

    If true, the listener will remove itself after the first time it is triggered.

  • [data] optional

    Arbitrary data that will be included as the second parameter when the listener is called.

  • [useCapture=false] Boolean optional

    For events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.

Returns:

Function:

Returns the anonymous function that was created and assigned as the listener. This is needed to remove the listener later using .removeEventListener.

play

(
  • src
  • [interrupt="none"|options]
  • [delay=0]
  • [offset=0]
  • [loop=0]
  • [volume=1]
  • [pan=0]
  • [startTime=null]
  • [duration=null]
)
AbstractSoundInstance static

Defined in play:1243

Play a sound and get a AbstractSoundInstance to control. If the sound fails to play, a AbstractSoundInstance will still be returned, and have a playState of PLAY_FAILED. Note that even on sounds with failed playback, you may still be able to call AbstractSoundInstance play, since the failure could be due to lack of available channels. If the src does not have a supported extension or if there is no available plugin, a default AbstractSoundInstance will be returned which will not play any audio, but will not generate errors.

Example

 createjs.Sound.on("fileload", handleLoad);
 createjs.Sound.registerSound("myAudioPath/mySound.mp3", "myID", 3);
 function handleLoad(event) {
     createjs.Sound.play("myID");
     // store off AbstractSoundInstance for controlling
     var myInstance = createjs.Sound.play("myID", {interrupt: createjs.Sound.INTERRUPT_ANY, loop:-1});
 }

NOTE to create an audio sprite that has not already been registered, both startTime and duration need to be set. This is only when creating a new audio sprite, not when playing using the id of an already registered audio sprite.

Parameters Deprecated
The parameters for this method are deprecated in favor of a single parameter that is an Object or PlayPropsConfig.

Parameters:

  • src String

    The src or ID of the audio.

  • [interrupt="none"|options] String | Object optional

    This parameter will be renamed playProps in the next release.
    This parameter can be an instance of PlayPropsConfig or an Object that contains any or all optional properties by name, including: interrupt, delay, offset, loop, volume, pan, startTime, and duration (see the above code sample).
    OR
    Deprecated How to interrupt any currently playing instances of audio with the same source, if the maximum number of instances of the sound are already playing. Values are defined as INTERRUPT_TYPE constants on the Sound class, with the default defined by defaultInterruptBehavior.

  • [delay=0] Number optional

    Deprecated The amount of time to delay the start of audio playback, in milliseconds.

  • [offset=0] Number optional

    Deprecated The offset from the start of the audio to begin playback, in milliseconds.

  • [loop=0] Number optional

    Deprecated How many times the audio loops when it reaches the end of playback. The default is 0 (no loops), and -1 can be used for infinite playback.

  • [volume=1] Number optional

    Deprecated The volume of the sound, between 0 and 1. Note that the master volume is applied against the individual volume.

  • [pan=0] Number optional

    Deprecated The left-right pan of the sound (if supported), between -1 (left) and 1 (right).

  • [startTime=null] Number optional

    Deprecated To create an audio sprite (with duration), the initial offset to start playback and loop from, in milliseconds.

  • [duration=null] Number optional

    Deprecated To create an audio sprite (with startTime), the amount of time to play the clip for, in milliseconds.

Returns:

AbstractSoundInstance:

A AbstractSoundInstance that can be controlled after it is created.

registerPlugins

(
  • plugins
)
Boolean static

Defined in registerPlugins:752

Register a list of Sound plugins, in order of precedence. To register a single plugin, pass a single element in the array.

Example

 createjs.FlashAudioPlugin.swfPath = "../src/soundjs/flashaudio/";
 createjs.Sound.registerPlugins([createjs.WebAudioPlugin, createjs.HTMLAudioPlugin, createjs.FlashAudioPlugin]);

Parameters:

  • plugins Array

    An array of plugins classes to install.

Returns:

Boolean:

Whether a plugin was successfully initialized.

registerSound

(
  • src
  • [id]
  • [data]
  • basePath
  • defaultPlayProps
)
Object static

Defined in registerSound:924

Available since 0.4.0

Register an audio file for loading and future playback in Sound. This is automatically called when using PreloadJS. It is recommended to register all sounds that need to be played back in order to properly prepare and preload them. Sound does internal preloading when required.

Example

 createjs.Sound.alternateExtensions = ["mp3"];
 createjs.Sound.on("fileload", handleLoad); // add an event listener for when load is completed
 createjs.Sound.registerSound("myAudioPath/mySound.ogg", "myID", 3);
 createjs.Sound.registerSound({ogg:"path1/mySound.ogg", mp3:"path2/mySoundNoExtension"}, "myID", 3);

Parameters:

  • src String | Object

    The source or an Object with a "src" property or an Object with multiple extension labeled src properties.

  • [id] String optional

    An id specified by the user to play the sound later. Note id is required for when src is multiple extension labeled src properties.

  • [data] Number | Object optional

    Data associated with the item. Sound uses the data parameter as the number of channels for an audio instance, however a "channels" property can be appended to the data object if it is used for other information. The audio channels will set a default based on plugin if no value is found. Sound also uses the data property to hold an AudioSprite array of objects in the following format {id, startTime, duration}.
    id used to play the sound later, in the same manner as a sound src with an id.
    startTime is the initial offset to start playback and loop from, in milliseconds.
    duration is the amount of time to play the clip for, in milliseconds.
    This allows Sound to support audio sprites that are played back by id.

  • basePath String

    Set a path that will be prepended to src for loading.

  • defaultPlayProps Object | PlayPropsConfig

    Optional Playback properties that will be set as the defaults on any new AbstractSoundInstance. See PlayPropsConfig for options.

Returns:

Object:

An object with the modified values that were passed in, which defines the sound. Returns false if the source cannot be parsed or no plugins can be initialized. Returns true if the source is already loaded.

registerSounds

(
  • sounds
  • basePath
)
Object static

Defined in registerSounds:985

Available since 0.6.0

Register an array of audio files for loading and future playback in Sound. It is recommended to register all sounds that need to be played back in order to properly prepare and preload them. Sound does internal preloading when required.

Example

    var assetPath = "./myAudioPath/";
 var sounds = [
     {src:"asset0.ogg", id:"example"},
     {src:"asset1.ogg", id:"1", data:6},
     {src:"asset2.mp3", id:"works"}
     {src:{mp3:"path1/asset3.mp3", ogg:"path2/asset3NoExtension}, id:"better"}
 ];
 createjs.Sound.alternateExtensions = ["mp3"];    // if the passed extension is not supported, try this extension
 createjs.Sound.on("fileload", handleLoad); // call handleLoad when each sound loads
 createjs.Sound.registerSounds(sounds, assetPath);

Parameters:

  • sounds Array

    An array of objects to load. Objects are expected to be in the format needed for registerSound: {src:srcURI, id:ID, data:Data} with "id" and "data" being optional. You can also pass an object with path and manifest properties, where path is a basePath and manifest is an array of objects to load. Note id is required if src is an object with extension labeled src properties.

  • basePath String

    Set a path that will be prepended to each src when loading. When creating, playing, or removing audio that was loaded with a basePath by src, the basePath must be included.

Returns:

Object:

An array of objects with the modified values that were passed in, which defines each sound. Like registerSound, it will return false for any values when the source cannot be parsed or if no plugins can be initialized. Also, it will return true for any values when the source is already loaded.

removeAllEventListeners

(
  • [type]
)

Removes all listeners for the specified type, or all listeners of all types.

Example

 // Remove all listeners
 displayObject.removeAllEventListeners();

 // Remove all click listeners
 displayObject.removeAllEventListeners("click");

Parameters:

  • [type] String optional

    The string type of the event. If omitted, all listeners for all types will be removed.

removeAllSounds

() static

Defined in removeAllSounds:1128

Available since 0.4.1

Remove all sounds that have been registered with registerSound or registerSounds.
Note this will stop playback on all active sound instances before deleting them.

Example

createjs.Sound.removeAllSounds();

removeEventListener

(
  • type
  • listener
  • [useCapture]
)

Removes the specified event listener.

Important Note: that you must pass the exact function reference used when the event was added. If a proxy function, or function closure is used as the callback, the proxy/closure reference must be used - a new proxy or closure will not work.

Example

 displayObject.removeEventListener("click", handleClick);

Parameters:

  • type String

    The string type of the event.

  • listener Function | Object

    The listener function or object.

  • [useCapture] Boolean optional

    For events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.

removeSound

(
  • src
  • basePath
)
Boolean static

Defined in removeSound:1034

Available since 0.4.1

Remove a sound that has been registered with registerSound or registerSounds.
Note this will stop playback on active instances playing this sound before deleting them.
Note if you passed in a basePath, you need to pass it or prepend it to the src here.

Example

 createjs.Sound.removeSound("myID");
 createjs.Sound.removeSound("myAudioBasePath/mySound.ogg");
 createjs.Sound.removeSound("myPath/myOtherSound.mp3", "myBasePath/");
 createjs.Sound.removeSound({mp3:"musicNoExtension", ogg:"music.ogg"}, "myBasePath/");

Parameters:

  • src String | Object

    The src or ID of the audio, or an Object with a "src" property, or an Object with multiple extension labeled src properties.

  • basePath String

    Set a path that will be prepended to each src when removing.

Returns:

Boolean:

True if sound is successfully removed.

removeSounds

(
  • sounds
  • basePath
)
Object static

Defined in removeSounds:1086

Available since 0.4.1

Remove an array of audio files that have been registered with registerSound or registerSounds.
Note this will stop playback on active instances playing this audio before deleting them.
Note if you passed in a basePath, you need to pass it or prepend it to the src here.

Example

    assetPath = "./myPath/";
 var sounds = [
     {src:"asset0.ogg", id:"example"},
     {src:"asset1.ogg", id:"1", data:6},
     {src:"asset2.mp3", id:"works"}
 ];
 createjs.Sound.removeSounds(sounds, assetPath);

Parameters:

  • sounds Array

    An array of objects to remove. Objects are expected to be in the format needed for removeSound: {srcOrID:srcURIorID}. You can also pass an object with path and manifest properties, where path is a basePath and manifest is an array of objects to remove.

  • basePath String

    Set a path that will be prepended to each src when removing.

Returns:

Object:

An array of Boolean values representing if the sounds with the same array index were successfully removed.

setDefaultPlayProps

(
  • src
  • playProps
)

Defined in setDefaultPlayProps:1441

Available since 0.6.1

Set the default playback properties for all new SoundInstances of the passed in src or ID. See PlayPropsConfig for available properties.

Parameters:

  • src String

    The src or ID used to register the audio.

  • playProps Object | PlayPropsConfig

    The playback properties you would like to set.

setMute

(
  • value
)
Boolean deprecated static

Defined in setMute:1405

Available since 0.4.0

Deprecated, please use muted instead.

Parameters:

  • value Boolean

    Whether the audio should be muted or not.

Returns:

Boolean:

If the mute was set.

setVolume

(
  • value
)
deprecated static

Defined in setVolume:1373

Deprecated, please use volume instead.

Parameters:

  • value Number

    The master volume value. The acceptable range is 0-1.

stop

() static

Defined in stop:1355

Stop all audio (global stop). Stopped audio is reset, and not paused. To play audio that has been stopped, call AbstractSoundInstance play.

Example

createjs.Sound.stop();

toString

() String

Inherited from EventDispatcher: toString:384

Returns:

String:

a string representation of the instance.

willTrigger

(
  • type
)
Boolean

Indicates whether there is at least one listener for the specified event type on this object or any of its ancestors (parent, parent's parent, etc). A return value of true indicates that if a bubbling event of the specified type is dispatched from this object, it will trigger at least one listener.

This is similar to hasEventListener, but it searches the entire event flow for a listener, not just this object.

Parameters:

  • type String

    The string type of the event.

Returns:

Boolean:

Returns true if there is at least one listener for the specified event.

Properties

_captureListeners

Object protected

_defaultPlayPropsHash

Object protected static

Defined in _defaultPlayPropsHash:607

Available since 0.6.1

An object hash storing PlayPropsConfig via the parsed source that is passed as defaultPlayProps in registerSound and registerSounds.

_idHash

Object protected static

Defined in _idHash:587

An object hash storing objects with sound sources, startTime, and duration via there corresponding ID.

_instances

Array protected static

Defined in _instances:574

An array containing all currently playing instances. This allows Sound to control the volume, mute, and playback of all instances when using static APIs like stop and setVolume. When an instance has finished playback, it gets removed via the Sound/finishedPlaying method. If the user replays an instance, it gets added back in via the _beginPlaying method.

_lastID

Number protected static

Defined in _lastID:565

Used internally to assign unique IDs to each AbstractSoundInstance.

_listeners

Object protected

Inherited from EventDispatcher: _listeners:99

_pluginsRegistered

Boolean protected static

Determines if the plugins have been registered. If false, the first call to play() will instantiate the default plugins (WebAudioPlugin, followed by HTMLAudioPlugin). If plugins have been registered, but none are applicable, then sound playback will fail.

Default: false

_preloadHash

Object protected static

Defined in _preloadHash:596

An object hash that stores preloading sound sources via the parsed source that is passed to the plugin. Contains the source, id, and data that was passed in by the user. Parsed sources can contain multiple instances of source, id, and data.

activePlugin

Object static

Defined in activePlugin:433

The currently active plugin. If this is null, then no plugin could be initialized. If no plugin was specified, Sound attempts to apply the default plugins: WebAudioPlugin, followed by HTMLAudioPlugin.

alternateExtensions

Array static

Defined in alternateExtensions:406

Available since 0.5.2

An array of extensions to attempt to use when loading sound, if the default is unsupported by the active plugin. These are applied in order, so if you try to Load Thunder.ogg in a browser that does not support ogg, and your extensions array is ["mp3", "m4a", "wav"] it will check mp3 support, then m4a, then wav. The audio files need to exist in the same location, as only the extension is altered.

Note that regardless of which file is loaded, you can call createInstance and play using the same id or full source path passed for loading.

Example

var sounds = [
    {src:"myPath/mySound.ogg", id:"example"},
];
createjs.Sound.alternateExtensions = ["mp3"]; // now if ogg is not supported, SoundJS will try asset0.mp3
createjs.Sound.on("fileload", handleLoad); // call handleLoad when each sound loads
createjs.Sound.registerSounds(sounds, assetPath);
// ...
createjs.Sound.play("myPath/mySound.ogg"); // works regardless of what extension is supported.  Note calling with ID is a better approach

capabilities

Object static

Defined in capabilities:509

Available since 0.6.1

Get the active plugins capabilities, which help determine if a plugin can be used in the current environment, or if the plugin supports a specific feature. Capabilities include:

  • panning: If the plugin can pan audio from left to right
  • volume; If the plugin can control audio volume.
  • tracks: The maximum number of audio tracks that can be played back at a time. This will be -1 if there is no known limit.

  • An entry for each file type in SUPPORTED_EXTENSIONS:
  • mp3: If MP3 audio is supported.
  • ogg: If OGG audio is supported.
  • wav: If WAV audio is supported.
  • mpeg: If MPEG audio is supported.
  • m4a: If M4A audio is supported.
  • mp4: If MP4 audio is supported.
  • aiff: If aiff audio is supported.
  • wma: If wma audio is supported.
  • mid: If mid audio is supported.

You can get a specific capability of the active plugin using standard object notation

Example

 var mp3 = createjs.Sound.capabilities.mp3;

Note this property is read only.

defaultInterruptBehavior

String static

Defined in defaultInterruptBehavior:393

Available since 0.4.0

Determines the default behavior for interrupting other currently playing instances with the same source, if the maximum number of instances of the sound are already playing. Currently the default is INTERRUPT_NONE but this can be set and will change playback behavior accordingly. This is only used when play is called without passing a value for interrupt.

Default: Sound.INTERRUPT_NONE, or "none"

EXTENSION_MAP

Object static

Defined in EXTENSION_MAP:365

Available since 0.4.0

Some extensions use another type of extension support to play (one of them is a codex). This allows you to map that support so plugins can accurately determine if an extension is supported. Adding to this list can help plugins determine more accurately if an extension is supported.

A useful list of extensions for each format can be found at http://html5doctor.com/html5-audio-the-state-of-play/.

Default: {m4a:"mp4"}

FILE_PATTERN

RegExp protected static

Defined in FILE_PATTERN:381

The RegExp pattern used to parse file URIs. This supports simple file names, as well as full domain URIs with query strings. The resulting match is: protocol:$1 domain:$2 path:$3 file:$4 extension:$5 query:$6.

INTERRUPT_ANY

String static

Defined in INTERRUPT_ANY:262

The interrupt value to interrupt any currently playing instance with the same source, if the maximum number of instances of the sound are already playing.

Default: any

INTERRUPT_EARLY

String static

Defined in INTERRUPT_EARLY:272

The interrupt value to interrupt the earliest currently playing instance with the same source that progressed the least distance in the audio track, if the maximum number of instances of the sound are already playing.

Default: early

INTERRUPT_LATE

String static

Defined in INTERRUPT_LATE:282

The interrupt value to interrupt the currently playing instance with the same source that progressed the most distance in the audio track, if the maximum number of instances of the sound are already playing.

Default: late

INTERRUPT_NONE

String static

Defined in INTERRUPT_NONE:292

The interrupt value to not interrupt any currently playing instances with the same source, if the maximum number of instances of the sound are already playing.

Default: none

muted

Boolean

Defined in muted:476

Available since 0.6.1

Mute/Unmute all audio. Note that muted audio still plays at 0 volume. This global mute value is maintained separately and when set will override, but not change the mute property of individual instances. To mute an individual instance, use AbstractSoundInstance muted instead.

Example

createjs.Sound.muted = true;

Default: false

PLAY_FAILED

String static

Defined in PLAY_FAILED:338

Defines the playState of an instance that failed to play. This is usually caused by a lack of available channels when the interrupt mode was "INTERRUPT_NONE", the playback stalled, or the sound could not be found.

Default: playFailed

PLAY_FINISHED

String static

Defined in PLAY_FINISHED:329

Defines the playState of an instance that completed playback.

Default: playFinished

PLAY_INITED

String static

Defined in PLAY_INITED:302

Defines the playState of an instance that is still initializing.

Default: playInited

PLAY_INTERRUPTED

String static

Defines the playState of an instance that was interrupted by another instance.

Default: playInterrupted

PLAY_SUCCEEDED

String static

Defined in PLAY_SUCCEEDED:311

Defines the playState of an instance that is currently playing or paused.

Default: playSucceeded

SUPPORTED_EXTENSIONS

ArrayString static

Defined in SUPPORTED_EXTENSIONS:348

Available since 0.4.0

A list of the default supported extensions that Sound will try to play. Plugins will check if the browser can play these types, so modifying this list before a plugin is initialized will allow the plugins to try to support additional media types.

NOTE this does not currently work for FlashAudioPlugin.

More details on file formats can be found at http://en.wikipedia.org/wiki/Audio_file_format.
A very detailed list of file formats can be found at http://www.fileinfo.com/filetypes/audio.

Default: ["mp3", "ogg", "opus", "mpeg", "wav", "m4a", "mp4", "aiff", "wma", "mid"]

volume

Number

Defined in volume:445

Available since 0.6.1

Set the master volume of Sound. The master volume is multiplied against each sound's individual volume. For example, if master volume is 0.5 and a sound's volume is 0.5, the resulting volume is 0.25. To set individual sound volume, use AbstractSoundInstance volume instead.

Example

createjs.Sound.volume = 0.5;

Default: 1

Events

fileerror

Defined in fileerror:643

Available since 0.6.0

This event is fired when a file fails loading internally. This event is fired for each loaded sound, so any handler methods should look up the event.src to handle a particular sound.

Event Payload:

  • target Object

    The object that dispatched the event.

  • type String

    The event type.

  • src String

    The source of the sound that was loaded.

  • [id] String optional

    The id passed in when the sound was registered. If one was not provided, it will be null.

  • [data] Number | Object optional

    Any additional data associated with the item. If not provided, it will be undefined.

fileload

Defined in fileload:631

Available since 0.4.1

This event is fired when a file finishes loading internally. This event is fired for each loaded sound, so any handler methods should look up the event.src to handle a particular sound.

Event Payload:

  • target Object

    The object that dispatched the event.

  • type String

    The event type.

  • src String

    The source of the sound that was loaded.

  • [id] String optional

    The id passed in when the sound was registered. If one was not provided, it will be null.

  • [data] Number | Object optional

    Any additional data associated with the item. If not provided, it will be undefined.