SoundInstance Class
A SoundInstance is created when any calls to the Sound API method play or createInstance are made. The SoundInstance is returned by the active plugin for control by the user.
Example
var myInstance = createjs.Sound.play("myAssetPath/mySrcFile.mp3");
A number of additional parameters provide a quick way to determine how a sound is played. Please see the Sound API method play for a list of arguments.
Once a SoundInstance is created, a reference can be stored that can be used to control the audio directly through the SoundInstance. If the reference is not stored, the SoundInstance will play out its audio (and any loops), and is then de-referenced from the Sound class so that it can be cleaned up. If audio playback has completed, a simple call to the play instance method will rebuild the references the Sound class need to control it.
var myInstance = createjs.Sound.play("myAssetPath/mySrcFile.mp3");
myInstance.addEventListener("complete", playAgain);
function playAgain(event) {
myInstance.play();
}
Events are dispatched from the instance to notify when the sound has completed, looped, or when playback fails
var myInstance = createjs.Sound.play("myAssetPath/mySrcFile.mp3");
myInstance.addEventListener("complete", handleComplete);
myInstance.addEventListener("loop", handleLoop);
myInstance.addEventListener("failed", handleFailed);
Constructor
Item Index
Methods
- _dispatchEvent
- addEventListener
- beginPlaying
- cleanup
- createAudioNode
- dispatchEvent
- getDuration
- getMute
- getPan
- getPosition
- getVolume
- hasEventListener
- init
- initialize
- interrupt
- mute deprecated
- off
- on
- pause
- play
- removeAllEventListeners
- removeEventListener
- resume
- sendEvent
- setMute
- setPan
- setPosition
- setVolume
- stop
- toString
- updateVolume
Properties
- _captureListeners
- _listeners
- delay
- delayTimeoutId
- gainNode
- muted
- offset
- onComplete deprecated
- onLoop deprecated
- onPlayFailed deprecated
- onPlayInterrupted deprecated
- onPlaySucceeded deprecated
- onReady deprecated
- owner
- pan
- pan
- panNode
- paused
- playState
- remainingLoops
- soundCompleteTimeout
- sourceNode
- sourceNodeNext
- src
- startTime
- uniqueId
- volume
Methods
_dispatchEvent
-
eventObj
-
eventPhase
addEventListener
-
type
-
listener
-
[useCapture]
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
StringThe string type of the event.
-
listener
Function | ObjectAn object with a handleEvent method, or a function that will be called when the event is dispatched.
-
[useCapture]
Boolean optionalFor events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.
beginPlaying
-
offset
-
loop
-
volume
-
pan
Called by the Sound class when the audio is ready to play (delay has completed). Starts sound playing if the src is loaded, otherwise playback will fail.
Parameters:
-
offset
NumberHow far into the sound to begin playback, in milliseconds.
-
loop
NumberThe number of times to loop the audio. Use -1 for infinite loops.
-
volume
NumberThe volume of the sound, between 0 and 1.
-
pan
NumberThe pan of the sound between -1 (left) and 1 (right). Note that pan does not work for HTML Audio.
cleanup
()
protected
Clean up the instance. Remove references and clean up any additional properties such as timers.
createAudioNode
-
startTime
-
offset
Creates an audio node using the current src and context, connects it to the gain node, and starts playback.
Parameters:
Returns:
dispatchEvent
-
eventObj
-
[target]
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 | EventAn 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 with the specified type.
-
[target]
Object optionalThe object to use as the target property of the event object. This will default to the dispatching object. This parameter is deprecated and will be removed.
Returns:
getDuration
()
Number
Get the duration of the instance, in milliseconds. Note in most cases, you need to play a sound using play or the Sound API Sound.play method before its duration can be reported accurately.
Example
var soundDur = myInstance.getDuration();
Returns:
getMute
()
Boolean
Get the mute value of the instance.
Example
var isMuted = myInstance.getMute();
Returns:
getPan
()
Number
NOTE that you can get volume directly, and getPan remains to allow support for IE8 with FlashPlugin.
Get the left/right pan of the instance. Note in WebAudioPlugin this only gives us the "x" value of what is actually 3D audio.
Example
var myPan = myInstance.getPan();
Returns:
getPosition
()
Number
Get the position of the playhead in the instance in milliseconds.
Example
var currentOffset = myInstance.getPosition();
Returns:
getVolume
()
NOTE that you can get volume directly, and getVolume remains to allow support for IE8 with FlashPlugin.
Get the volume of the instance. The actual output volume of a sound can be calculated using:
myInstance.getVolume() * createjs.Sound.getVolume();
Returns:
hasEventListener
-
type
Indicates whether there is at least one listener for the specified event type and useCapture
value.
Parameters:
-
type
StringThe string type of the event.
Returns:
init
-
src
-
owner
Initialize the SoundInstance. This is called from the constructor.
Parameters:
-
src
StringThe source of the audio.
-
owner
ClassThe plugin that created this instance.
initialize
()
protected
Initialization method.
interrupt
()
protected
The sound has been interrupted.
mute
-
value
REMOVED. Please use setMute instead.
Parameters:
-
value
BooleanIf the sound should be muted or not.
Returns:
off
-
type
-
listener
-
[useCapture]
A shortcut to the removeEventListener method, with the same parameters and return value. This is a companion to the .on method.
on
-
type
-
listener
-
[scope]
-
[once=false]
-
[data]
-
[useCapture=false]
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 created anonymous function is returned for use with .removeEventListener (or .off).
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
StringThe string type of the event.
-
listener
Function | ObjectAn object with a handleEvent method, or a function that will be called when the event is dispatched.
-
[scope]
Object optionalThe 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 optionalIf true, the listener will remove itself after the first time it is triggered.
-
[data]
optionalArbitrary data that will be included as the second parameter when the listener is called.
-
[useCapture=false]
Boolean optionalFor events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.
Returns:
pause
()
Boolean
Pause the instance. Paused audio will stop at the current time, and can be resumed using resume.
Example
myInstance.pause();
Returns:
play
-
[interrupt="none"|options]
-
[delay=0]
-
[offset=0]
-
[loop=0]
-
[volume=1]
-
[pan=0]
Play an instance. This method is intended to be called on SoundInstances that already exist (created with the Sound API createInstance or play).
Example
var myInstance = createjs.Sound.createInstance(mySrc);
myInstance.play(createjs.Sound.INTERRUPT_ANY);
// alternatively, we can pass in options we want to set in an object
myInstance.play({offset:1, loop:2, pan:0.5});
Parameters:
-
[interrupt="none"|options]
String | Object optionalHow 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 Sound/defaultInterruptBehavior.
OR
This parameter can be an object that contains any or all optional properties by name, including: interrupt, delay, offset, loop, volume, and pan (see the above code sample). -
[delay=0]
Number optionalThe delay in milliseconds before the sound starts
-
[offset=0]
Number optionalHow far into the sound to begin playback, in milliseconds.
-
[loop=0]
Number optionalThe number of times to loop the audio. Use -1 for infinite loops.
-
[volume=1]
Number optionalThe volume of the sound, between 0 and 1.
-
[pan=0]
Number optionalThe pan of the sound between -1 (left) and 1 (right). Note that pan is not supported for HTML Audio.
removeAllEventListeners
-
[type]
Removes all listeners for the specified type, or all listeners of all types.
Example
// Remove all listeners
displayObject.removeAllEvenListeners();
// Remove all click listeners
displayObject.removeAllEventListeners("click");
Parameters:
-
[type]
String optionalThe string type of the event. If omitted, all listeners for all types will be removed.
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);
resume
()
Boolean
Resume an instance that has been paused using pause. Audio that has not been paused will not playback when this method is called.
Example
myInstance.pause();
// do some stuff
myInstance.resume();
Returns:
sendEvent
-
type
A helper method that dispatches all events for SoundInstance.
Parameters:
-
type
StringThe event type
setMute
-
value
Mute and unmute the sound. Muted sounds will still play at 0 volume. Note that an unmuted sound may still be silent depending on Sound volume, instance volume, and Sound mute.
Example
myInstance.setMute(true);
Parameters:
-
value
BooleanIf the sound should be muted.
Returns:
setPan
-
value
NOTE that you can set pan directly, and getPan remains to allow support for IE8 with FlashPlugin.
Set the left(-1)/right(+1) pan of the instance. Note that HTMLAudioPlugin does not support panning, and only simple left/right panning has been implemented for WebAudioPlugin. The default pan value is 0 (center).
Example
myInstance.setPan(-1); // to the left!
Parameters:
-
value
NumberThe pan value, between -1 (left) and 1 (right).
Returns:
setPosition
-
value
Set the position of the playhead in the instance. This can be set while a sound is playing, paused, or even stopped.
Example
myInstance.setPosition(myInstance.getDuration()/2); // set audio to its halfway point.
Parameters:
-
value
NumberThe position to place the playhead, in milliseconds.
setVolume
-
value
NOTE that you can set volume directly, and setVolume remains to allow support for IE8 with FlashPlugin. Set the volume of the instance. You can retrieve the volume using getVolume.
Example
myInstance.setVolume(0.5);
Note that the master volume set using the Sound API method setVolume will be applied to the instance volume.
Parameters:
-
value
ObjectThe volume to set, between 0 and 1.
Returns:
Properties
delay
Number
protected
The time in milliseconds before the sound starts. Note this is handled by Sound.
Default: 0
delayTimeoutId
TimeoutVariable
protected
A Timeout created by Sound when this SoundInstance is played with a delay. This allows SoundInstance to remove the delay if stop or pause or cleanup are called before playback begins.
Default: null
gainNode
AudioGainNode
NOTE this only exists as a WebAudioPlugin property and is only intended for use by advanced users.
GainNode for controlling SoundInstance
volume. Connected to the WebAudioPlugin gainNode
that sequences to context.destination
.
Default: null
offset
Number
protected
How far into the sound to begin playback in milliseconds. This is passed in when play is called and used by pause and setPosition to track where the sound should be at. Note this is converted from milliseconds to seconds for consistency with the WebAudio API.
Default: 0
pan
Number
The pan of the sound, between -1 (left) and 1 (right). Note that pan does not work for HTML Audio. Note this uses a getter setter, which is not supported by Firefox versions 3.6 or lower, Opera versions 11.50 or lower, and Internet Explorer 8 or lower. Instead use setPan and getPan. Note in WebAudioPlugin this only gives us the "x" value of what is actually 3D audio.
Default: 0
pan
Number
protected
The length of the audio clip, in milliseconds. Use getDuration to access.
Default: 0
panNode
AudioPannerNode
NOTE this only exists as a WebAudioPlugin property and is only intended for use by advanced users. A panNode allowing left and right audio channel panning only. Connected to SoundInstance gainNode.
Default: null
playState
String
The play state of the sound. Play states are defined as constants on Sound.
Default: null
remainingLoops
Number
protected
The number of play loops remaining. Negative values will loop infinitely.
Default: 0
soundCompleteTimeout
TimeoutVariable
protected
Timeout that is created internally to handle sound playing to completion. Stored so we can remove it when stop, pause, or cleanup are called
Default: null
sourceNode
AudioNode
NOTE this only exists as a WebAudioPlugin property and is only intended for use by advanced users. sourceNode is the audio source. Connected to gainNode.
Default: null
sourceNodeNext
AudioNode
protected
NOTE this only exists as a WebAudioPlugin property and is only intended for use by advanced users. sourceNodeNext is the audio source for the next loop, inserted in a look ahead approach to allow for smooth looping. Connected to gainNode.
Default: null
startTime
Number
protected
WebAudioPlugin only. Time audio started playback, in seconds. Used to handle set position, get position, and resuming from paused.
Default: 0
volume
Number
The volume of the sound, between 0 and 1. Note this uses a getter setter, which is not supported by Firefox versions 3.6 or lower and Opera versions 11.50 or lower, and Internet Explorer 8 or lower. Instead use setVolume and getVolume.
The actual output volume of a sound can be calculated using:
myInstance.volume * createjs.Sound.getVolume();
Default: 1
Events
complete
The event that is fired when playback completes. This means that the sound has finished playing in its entirety, including its loop iterations.
failed
The event that is fired when playback has failed. This happens when there are too many channels with the same src property already playing (and the interrupt value doesn't cause an interrupt of another instance), or the sound could not be played, perhaps due to a 404 error.
interrupted
The event that is fired when playback is interrupted. This happens when another sound with the same src property is played using an interrupt value that causes this instance to stop playing.
loop
The event that is fired when a sound has completed playing but has loops remaining.
ready
The event that is fired when a sound is ready to play.