SoundManager 2: Documentation
SoundManager Configuration
Flash URLs, version + performance options
SoundManager Properties
SoundManager includes a few global parameters which configure debug mode, flash movie path and other behaviours. At minimum, the url
property must assigned a path used to look for the necessary flash movie.
soundManager.allowPolling = true; // enable flash status updates. Required for whileloading/whileplaying.
soundManager.consoleOnly = false; // if console is being used, do not create/write to #soundmanager-debug
soundManager.debugMode = true; // enable debugging output (div#soundmanager-debug, OR console..)
soundManager.flashLoadTimeout =1000;// ms to wait for flash movie to load before failing (0 = infinity)
soundManager.flashVersion = 8; // version of flash to require, either 8 or 9. Some features require 9.
soundManager.nullURL = 'null.mp3'; // (Flash 8 only): URL of silent/blank MP3 for unloading/stop request.
soundManager.url = '/path/to/swf/'; // path (directory) where SM2 .SWF files will be found.
soundManager.useConsole = true; // use firebug/safari console.log()-type debug console if available
soundManager.useMovieStar = false; // enable (beta) support for Flash 9.0r115+ MPEG4 audio + video
soundManager.useFastPolling = false;// fast timer=higher callback frequency, combine w/useHighPerformance
soundManager.useHighPerformance = false;// position:fixed flash movie for faster JS/flash callbacks
soundManager.waitForWindowLoad = false; // always delay soundManager.onload() until after window.onload()
soundManager.wmode = 'transparent'; // null, transparent, opaque (last two allow HTML on top of flash)
soundManager.allowFullScreen = true; // enter full-screen (via double-click on movie) for flash 9+ video
To modify global SoundManager default paramaters for SM2 itself or for all sound objects, edit the main soundmanager2.js file (look for above section in code) or assign new values in your own application script before either window.onDOMContentLoaded()
or window.onload()
fire. (Specifically, both external and inline script blocks which immediately execute are OK.)
Example per-application override:
soundManager.debugMode = false; // disable debug mode
soundManager.defaultOptions.volume = 33; // set global default volume for all sound objects
soundManager.debugMode
soundManager.debugMode
configures SM2's debug behaviour, enabled (true) by default. When enabled, SoundManager 2 will write console-like output to console.log()
-style javascript interfaces, and/or an HTML element with the ID soundmanager-debug
(will be created if not found in the DOM at runtime.)
For a live example of debug output, see Debug + Console Output.
soundManager.url
soundManager.url
specifies the "online", generally HTTP-based path which SM2 will load .SWF movies from. The "local" (current) directory will be used by default. The appropriate .SWF required (depending on the desired Flash version) will be appended to the URL.
Example: soundManager.url = '/path/to/swf/';
(Note trailing slash)
For cases where SM2 is being used "offline" in non-HTTP cases (eg., development environments), see altURL
.
soundManager.altURL
soundManager.altURL
specifies an alternate path to soundManager.url
which SM2 can load its SWF from. It is a simple convenience for when you may need to load SWFs from different paths depending on your hosting environment (eg., offline development vs. production.)
Example: soundManager.altURL = '../';
(Load from parent directory - note trailing slash)
For altURL to be used, it must be defined and an "alternate environment" condition must be met:
soundManager.useAltURL = (!document.location.protocol.match(/http/i));
By default and as shown above, SM2 will use this property when the hosting page is not being served over HTTP, and thus is assumed to being served "offline" - for example, when loading via file://, from the local file system.
This can easily be adapted to taste, eg., checking the domain matching yourdomain.com vs. localhost:
soundManager.useAltURL = (!document.location.match(/mydomain.com/i));
If soundManager.altURL
is null (the default), soundManager.url
will be used for all cases.
soundManager.flashVersion
SoundManager 2 started with a Flash 8 base requirement, but can also now use Flash 9 and take advantages of some new features Flash 9 offers. By default Flash 8 will be used, but the version can be easily changed by setting flashVersion
appropriately.
Example: soundManager.flashVersion = 9;
The Flash 8 version is soundmanager2.swf
, and the flash 9 version is soundmanager2_flash9.swf
, accordingly. Note that only Flash 8 and Flash 9 are supported at this time; other values will result in errors.
New Flash 9-only features:
- MPEG-4 (HE-AAC/H.264) video and audio support
- True "multi-shot" sound behaviour.
play()
can be called multiple times, giving a layered, "chorus" effect. Sound will also fireonfinish()
multiple times. (Previous behaviour did not layer sounds, but would re-play a single instance.) waveformData
array: 256 waveform data values available while playing soundeqData
array: 256 EQ spectrum data values available while playing soundpeakData
object: Left and right channel peak/volume data available while playing sound
soundManager.flashLoadTimeout
After initializing the flash component during start-up, SM2 will wait for a defined period of time before timing out and calling soundManager.onerror()
.
The default value is 1000 (msec.) Setting a value of 0 disables the timeout and makes SM2 wait indefinitely for a call from the flash component.
Setting this parameter to 0 may be useful when attempting to gracefully recover from a flashBlock situation, where the user has whitelisted the movie after it was blocked etc.
Note that when the timeout is disabled, soundManager will not fire its onerror() handler if there is an error at the flash loading stage.
soundManager.useFastPolling
By default useFastPolling = false
, and thus SoundManager uses a 20-milisecond timer inside Flash when polling for updated sound properties such as bytesLoaded
and data and event callbacks eg. whileloading()
, whileplaying()
and so on. With useFastPolling = true
, a 1-msec timer is used and callback frequency may noticeably increase. This is best combined with useHighPerformance
for optimal results.
soundManager.useHighPerformance
Perhaps intuitively, Flash is given higher priority when positioned within the viewable area of the browser, at least 6px in height (oddly), fully-opaque, visible and displayed on the screen. By default, soundManager.useHighPerformance
is enabled and should noticeably reduce JS/flash lag and increase the frequency of callbacks such as whileplaying()
in some circumstances.
soundManager.useHighPerformance = true;
This has made a noticeable impact in responsiveness on Mac OS X, and Safari on Windows; animation lag is practically non-existent (see demo). Because setting wmode=transparent and fixed position has been reported to cause some issues, the feature is disabled by default.
To be least-obtrusive, SM2 attempts to set position:fixed, and uses bottom/left:0px to stay within view (though using wmode=transparent where possible, to be hidden from view.) It occupies an 8x8px square. If you wish to position the movie yourself or show it inline, perhaps for playing video, have a DIV element with the ID of sm2-container
present in the DOM for SM2 to reference and it will write the movie there without positioning.
soundManager.wmode
The wmode
property is applied directly to the flash movie, and can be either null
, 'window'
, 'transparent'
or 'opaque'
. By default if useHighPerformance
is enabled, transparency will be attempted by SM2 unless there are known issues with the rendering mode.
It appears that non-IE browsers on Windows will not load SWF content "below the fold" (out of scrollable view) when wmode is set to anything other than null (window). This will break SM2 as it expects Flash to load within a reasonably short amount of time - so SM2 by default will reset wmode for this case. If you wish to force retention of your wmode
, set soundManager.flashTimeout = 0
which will ensure that if the content is below the fold, SM2 will not time out waiting for it to load.
Additionally, soundManager.specialWmodeCase
will be set to true
if wmode has been reset due to this special condition.
soundManager.allowFullScreen
With allowFullScreen
enabled, Flash 9+ (MovieStar) video can be displayed at full-screen size. Currently the movie must be double-clicked to trigger full-screen mode. When full-screen is entered and left, soundManager.isFullScreen
is updated to reflect the state.
SoundManager Core API
Methods for the soundManager object.
SoundManager Global Object
This is a collection of methods, collections, properties and event handlers available via the soundManager Javascript object. Sound properties and methods can be set on a global (inherited) default, or per-sound basis.
- canplay:boolean canPlayURL(mediaURL:string)
- Returns a boolean indicating whether soundManager can play the given URL. Playability is determined by a matching URL pattern set at runtime, based on Flash version and MPEG4 (MovieStar mode) support.
- Example:
var sURL = '/path/to/some.mp3'; if (soundManager.canPlayURL(sURL)) { soundManager.createSound('fooSound',sURL); }
- object:SMSound createSound(object:options)
- Creates a sound with an arbitrary number of optional arguments. Returns a
SMSound
object instance. -
Example:
soundManager.createSound({ id: 'mySound', // required url: '/audio/mysoundfile.mp3', // required // optional sound parameters here, see Sound Properties for full list volume: 50, autoPlay: true, whileloading: soundIsLoading });
Each
createSound()
call results in the creation of aSMSound
object which stores all properties, methods and events relevant to that particular sound instance.Individual sound objects can also easily be referenced as returned from
createSound()
:var mySoundObject = soundManager.createSound({ id: 'mySound', url: '/audio/mysoundfile.mp3' }); mySoundObject.play(); // SMSound object reference, same as soundManager.getSoundById('mySound')
(Note: Code formatting is stylistic, not necessarily recommended.) See Object Literal Format.
- createSound(id:string,url:string)
- Creates a sound with the specified ID and URL (simple method.)
- Example:
soundManager.createSound('mySound','/audio/mysoundfile.mp3');
- object:SMSound createVideo(object:options)
- Creates a video with an arbitrary number of optional arguments. Returns a
SMSound
object instance which supports video. - Functionally identical to
createSound()
, only with video parameters enabled. Flash 9.0r115+ required, SM2 "movieStar" mode and useVideo parameters must be enabled. - Example:
soundManager.createVideo({ id: 'myVideo', // required url: '/video/mymovie.mp4', // required // optional sound parameters here, see Sound Properties for full list volume: 50, autoPlay: true, onmetadata: handleMetaData, // special video-only event handler (width/height info, etc.) whileloading: videoIsLoading // remember to omit comma on the last item });
- destroySound(id:string)
- Stops, unloads and destroys a sound specified by ID.
- Example:
soundManager.destroySound('mySound');
- destroyVideo(id:string)
- Stops, unloads and destroys a video specified by ID.
- Example:
soundManager.destroyVideo('myVideo');
- mute([id:string])
- Mutes the sound specified by ID. If no ID specified, all sounds will be muted. Affects muted property (boolean.)
- Example:
soundManager.mute('mySound');
- onready(callback:function(status),[scope])
- Queue
onload()
-style event listener(s) processed at (or immediately, if added after) SM2 initialization, just beforesoundManager.onload()
oronerror()
are called. More flexible than singlesoundManager.onload()
event, allows separate scripts to add listeners etc. An optional scope parameter can be specified; if none, the callback is scoped to the window. - Example:
soundManager.onready(myOnReadyHandler); soundManager.onready(myOtherHandler);
- A "status" object is also passed to the callback, which can be safely ignored. It includes a "success" parameter, indicating the state of
soundManager.isSupported()
. - Example:
soundManager.onready(function(oStatus){ if (oStatus.success) { alert('Yay, SM2 loaded OK!'); } else { alert('Oh snap, SM2 could not start.'); } });
- The same listener may be added multiple times; there is no duplicate checking. Queue is processed in order of addition.
- If
soundManager.reboot()
is called, all listeners' "fired" flags will be reset and they will be eligible to fire again when SM2 starts up.
- didCreate:boolean play(id:string,[options object])
- Starts playing the sound specified by ID. (Will start loading if applicable, and will play ASAP.)
- Optionally, returns a boolean value indicating "sound created", ie. if the related sound object didn't exist prior to this call and was created to do so.
- Example:
soundManager.play('mySound');
- Note that the second parameter,
options object
, is not required and can take almost any argument from the object literal format (eg. volume.) It is convenient when you wish to override the sound defaults for a single instance. - Example:
soundManager.play('mySound',{volume:50,onfinish:playNextSound});
- pause(id:string)
- Pauses the sound specified by ID. Does not toggle. Affects paused property (boolean.)
- Example:
soundManager.pause('mySound');
- pauseAll()
- Pauses all sounds whose playState is >0. Affects paused property (boolean.)
- Example:
soundManager.pause();
- reboot()
- Destroys any created SMSound objects, unloads the flash movie (removing it from the DOM) and restarts the SM2 init process, retaining all currently-set properties.
- Example:
soundManager.onerror = function() { // Something went wrong during init - in this example, we *assume* flashblock etc. soundManager.flashLoadTimeout = 0; // When restarting, wait indefinitely for flash soundManager.onerror = {}; // Prevent an infinite loop, in case it's not flashblock soundManager.reboot(); // and, go! }
- This method may be helpful when trying to gracefully recover from FlashBlock-type situations where the user has prevented the SWF from loading, but is able to whitelist it. For more ideas, see Flashblock demo.
- When using this method also consider flashLoadTimeout, which can have SM2 wait indefinitely for the flash to load if desired.
- resume(id:string)
- Resumes the currently-paused sound specified by ID.
- Example:
soundManager.resume('mySound');
- resumeAll()
- Resumes all currently-paused sounds.
- Example:
soundManager.resumeAll();
- setPan(id:string,volume:integer)
- Sets the stereo pan (left/right bias) of the sound specified by ID. Accepted values: -100 to 100 (L/R, 0 = center.) Affects pan property.
- Example:
soundManager.setPan('mySound',-80);
- setPosition(id:string,msecOffset:integer)
- Seeeks to a given position within a sound, specified by miliseconds (1000 msec = 1 second.) Affects position property.
- Example:
soundManager.setPosition('mySound',2500);
- Can only seek within loaded sound data, as defined by the duration property.
- setVolume(id:string,volume:integer)
- Sets the volume of the sound specified by ID. Accepted values: 0-100. Affects volume property.
- Example:
soundManager.setVolume('mySound',50);
- stop(id:string)
- Stops playing the sound specified by ID.
- Example:
soundManager.stop('mySound');
- stopAll()
- Stops any currently-playing sounds.
- Example:
soundManager.stopAll();
- toggleMute(id:string)
- Mutes/unmutes the sound specified by ID.
- Example:
soundManager.toggleMute('mySound');
- togglePause(id:string)
- Pauses/resumes play on the sound specified by ID.
- Example:
soundManager.togglePause('mySound');
- unload(id:string)
- Stops loading the sound specified by ID, canceling any current HTTP request.
- Example:
soundManager.unload('mySound');
- Note that for Flash 8, SoundManager does this by loading a new, tiny "stub" MP3 file,
./null.mp3
, which replaces the current one from loading. This is defined in the SM2 global object asnullURL
, and can be edited.
- unmute([id:string])
- Unmutes the sound specified by ID. If no ID specified, all sounds will be unmuted. Affects muted property (boolean.)
- Example:
soundManager.unmute('mySound');
- object:SMSound getSoundById(id:string)
- Returns an
SMSound
object specified by ID, or null if there is a problem. - Example:
var mySMSound = soundManager.getSoundById('mySound');
- number:bytesUsed getMemoryUse()
- Returns the total number of bytes allocated to the Adobe Flash player or Adobe AIR, or 0 if unsupported (Flash 9+ only.) This number may include memory use across all tabs, browsers etc. See system.totalMemory (livedocs.adobe.com)
- Example:
var mbUsed = (soundManager.getMemoryUse()/1024/1024).toFixed(2); // eg. 12.05 MB
- loadFromXML(xmlURL:string)
- Loads and creates sounds as defined in a SoundManager v1 XML file (legacy)
- Note that per-sound options are not supported with this method, and sound objects will be created immediately upon loading and parsing of the XML. The sounds will inherit the
defaultOptions
settings, with the exception of thestream
attribute as set in the XML (true if defined, defaultOption applied if omitted.) - Example:
soundManager.loadFromXML('/path/to/some.xml');
- XML format example: MPC drumkit XML file
- isSupported:boolean supported()
- Returns a boolean indicating whether soundManager has attempted to and succeeded in initialising. This function will return false if called before initialisation has occurred.
- Example:
var isSupported = soundManager.supported();
SMSound (Sound Object) API
Each createSound()
call generates a matching SMSound
(sound instance) object, which lasts for the life of the page or until explicitly destroyed. Each instance stores stateful information (eg. playState
) and provides event handlers for state changes (eg. onload()
.)
SoundManager is a convenient wrapper for most sound object methods: It will check for and gracefully exit if a sound object (specified by ID) does not exist, and provides convenient global functionality, eg. muting or pausing of all sounds.
Nonetheless, each SMSound
object can have its methods called directly. eg. mySound.mute()
instead of soundManager.mute('mySound')
, and so on.
Note that for code examples, mySound
is assumed to be a valid SMSound instance object - eg.,var mySound = soundManager.createSound();
or
var mySound = soundManager.getSoundById();
Sound Object Methods
Each sound under SoundManager 2 is given a SMSound
object instance which includes the following events, methods and properties.
- destroy()
- Stops, unloads and destroys a sound.
- Example:
mySound.destroy();
- play([options object])
- Starts playing the given sound, with an optional options object. (Will start loading if applicable, and will play ASAP.)
- Note that the
options object
parameter is not required and can take almost any argument from the object literal format (eg. volume.) - Example:
mySound.play('mySound',{volume:50,onfinish:playNextSound});
- setPosition(msecOffset:integer)
- Seeeks to a given position within a sound, specified by miliseconds (1000 msec = 1 second.) Affects position property.
- Example:
mySound.setPosition(2500);
- Can only seek within loaded sound data, as defined by the duration property.
- pause()
- Pauses the given sound. (Does not toggle.) Affects paused property (boolean.)
- Example:
mySound.pause();
- resume()
- Resumes the currently-paused sound. Does not affect currently-playing sounds.
- Example:
mySound.resume();
- toggleMute()
- Mutes/unmutes the given sound. Affected muted property (boolean.)
- Example:
mySound.toggleMute();
- togglePause()
- Pauses/resumes play of the given sound. Will also start a sound if it is has not yet been played.
- Example:
mySound.togglePause();
- setVolume(volume:integer)
- Sets the volume of the given sound. Accepted values: 0-100. Affects volume property.
- Example:
mySound.setVolume(50);
- mute()
- Mutes the given sound. Affects muted property.
- Example:
mySound.mute();
- unmute()
- Unmutes the given sound. Affects muted property.
- Example:
mySound.unmute();
- setPan(volume:integer)
- Sets the stereo pan (left/right bias) of the given sound. Accepted values: -100 to 100 (L/R, 0 = center.) Affects pan property.
- Example:
mySound.setPan(-80);
- stop()
- Stops playing the given sound.
- Example:
mySound.stop();
- unload()
- Stops loading the given sound, canceling any current HTTP request.
- Example:
mySound.unload();
- Note that for Flash 8, SoundManager does this by loading a new, tiny "stub" MP3 file,
./null.mp3
, which replaces the current one from loading. This is defined in the SM2 global object asnullURL
, and can be edited.
SMSound Events
Event handlers for SMSound objects.
Sound Object Events
Like native javascript objects, each SoundManager SMSound
(sound instance) object can fire a number of events including onload
and others. Functions can be assigned and will be called as needed, and are scoped to the relevant sound object. Specifically, the this
keyword will point to the sound object on which the event fired such that its properties can easily be accessed - eg. within an SMSound
event handler, this.sID
will give the sound ID.
- onload(boolean:success)
- Fires on sound load. Boolean reflects successful load (true), or fail/load from cache (false).
- False value should seemingly only be for failure, but appears to be returned for load from cache as well. This strange behaviour comes from Flash. More detail may be available from the Flash 8 sound object documentation.
- Failure can occur if the Flash sandbox (security) model is preventing access, for example loading SoundManager 2 on the local file system and trying to access an MP3 on a network (or internet) URL. (Security can be configured in the Flash security panel, [see here].)
- whileloading()
- Fires at a regular interval when a sound is loading and new data has been received. The relevant, updated property is
bytesLoaded
. - Example handler code:
soundManager._writeDebug('sound '+this.sID+' loading, '+this.bytesLoaded+' of '+this.bytesTotal);
- Note that the
duration
property starts from 0 and is updated duringwhileloading()
to reflect the duration of currently-loaded sound data (ie. when a 4:00 MP3 has loaded 50%, the duration will be reported as 2:00 in milliseconds.) However, an estimate of final duration can be calculated usingbytesLoaded
,bytesTotal
andduration
while loading. Once fully-loaded,duration
will reflect the true and accurate value.
- onbufferchange()
- Fires when a sound's reported buffering state has changed while playing and/or loading. The current state is reflected in the boolean
isBuffering
property. - Flash 9+ only. Related information on Adobe, Sound.isBuffering.
- ondataerror()
- Fires at least once per sound play instance when Flash encounters a security error when trying to call computeSpectrum() internally. This typically happens when sounds are 'inaccessible' due to another Flash movie (eg. YouTube) in another tab which has loaded, and may (or may not be) playing sound. Flash attempts to read the "combined" output to the sound card, and must have security permissions for all sounds as a result. See areSoundsInaccessible() on Adobe for more info.
- If the offending resource causing the security error is closed or becomes inactive(?), the data will become available again. Intermittent availability will result in intermittent calls to
ondataerror()
.
- onplay()
- Fires when
sound.play()
is called.
- onpause()
- Fires when a sound pauses, eg. via
sound.pause()
. - Example:
soundManager.pause('mySound');
- onresume()
- Fires when a sound resumes playing, eg. via
sound.resume()
. - Example:
soundManager.resume('mySound');
- onstop()
- Fires when
sound.stop()
is explicitly called. For natural "sound finished"onfinish()
case, see below.
- onfinish()
- Fires when a playing sound has reached its end. By this point, relevant properties like
playState
will have been reset to non-playing status.
- onbeforefinishcomplete()
- Fires when a sound has finished,
onfinish()
has been called, but before the sound play state and other meta data (position, etc.) are reset.
- onbeforefinish()
- Fires when a playing, fully-loaded sound has reached
onbeforefinishtime
(eg. 5000 msec) from its end.
- onjustbeforefinish()
- Fires approximately
justbeforefinishtime
before the end of a fully-loaded, playing sound. - This is based on a polling approach given SM2 must track the sound's position, and is approximated (eg. a 200 msec value may fire at 187 msec before the end of the sound.)
- onid3()
- Fires when ID3 data has been received. Relevant property is
id3
, which is an object literal (JSON)-style object. Only fields with data will be populated. - Note that ID3V2 data is located at the beginning (header) of an MP3 file and will load almost immediately, whereas ID3V1 data is at the end and will not be received until the MP3 has fully loaded.
-
Example handler code:
soundManager._writeDebug('sound '+this.sID+' ID3 data received'); var prop = null; var data = ''; for (prop in this.id3) { data += prop+': '+this.id3[prop]+','; // eg. title: Loser, artist: Beck }
- Refer to the Flash 8 Sound.id3 documentation for a list of ID3 properties.
- When parsing ID3 data, it is best to check for the existance of ID3V1 data first, and apply ID3V2 if no matching ID3V1 data is defined. (V1 should "inherit" from V2, ideally, if available.)
- Note that Flash's cross-domain security restrictions may prevent access to ID3 information, even though the MP3 itself can be loaded. (crossdomain.xml files on the remote host can grant Flash permission to access this.)
- Also note some issues with parsing ID3 from iTunes.
SMSound Properties
Instance Option properties (parameters) can be used with createSound()
and play()
.
Example:
soundManager.createSound({
id: 'foo',
url: '/path/to/an.mp3'
});
Dynamic Properties can be read to monitor the state of a sound object.
Example:
alert(mySound.playState);
Sound Object Properties
Each sound object inherits these properties from soundManager.defaultOptions. They can be set individually or at once when enclosed in object literal form to either createSound()
or play()
.
- sID
- Sound ID string as provided from the
id
parameter viacreateSound()
orplay()
. Can be referenced asthis.sID
from within sound object event handlers such asonload()
,whileloading()
orwhileplaying()
, etc. - If an ID is known, the related SMSound object can be retrieved via
getSoundById
or directly referencingsounds[sID]
on the SoundManager global object.
- url
- The specified URL from which the sound is loaded. Can be referenced as
this.url
from within sound object event handlers such asonload()
orwhileplaying()
, etc.
- id3
- An object literal populated, if applicable, when ID3 data is received (related handler:
onid3()
) - For property details, see onid3().
- bytesLoaded
- The number of bytes currently received while loading a sound.
- bytesTotal
- The total number of bytes to be downloaded, while loading a sound.
- position
- The current location of the "play head" within the sound, specified in milliseconds (1 sec = 1000 msec).
- duration
- The current length of the sound, specified in milliseconds.
- Note that during loading, this property reflects the length of downloaded data, not the full length, until completely loaded (see whileloading().) For an approximate "full duration" value while loading, see
durationEstimate
.
- durationEstimate
- The estimated duration of the sound, specified in milliseconds.
- Due to the dynamic nature of
duration
while loading, this attempts to provide the full duration by calculatingparseInt((self.bytesTotal/self.bytesLoaded)*self.duration)
and is updated with eachwhileloading()
interval. - Once the sound has fully loaded,
duration
should be referenced as it will contain the final and accurate value. - Note that this method works only with Constant Bitrate (CBR)-encoded MP3s due to the consistent data/time assumption. VBR-encoded MP3s will give inaccurate results.
- isBuffering
- Boolean value reflecting the buffering state of a playing or loading object. To be notified when this property changes, see onbufferchange().
- Flash 9+ only. Related information on Adobe, Sound.isBuffering.
- loaded
- Boolean value indicating load success as returned from Flash. True indicates success, False is a failure.
- Because of the potential for false positives,
duration
and other properties could be checked as a test of whether sound data actually loaded. For more granular state information, see readyState.
- muted
- Boolean indicating muted status. True/False.
- Treat as read-only; use
mute()
,unmute()
andtoggleMute()
methods to affect state.
- playState
- Numeric value indicating the current playing state of the sound.
- 0 = stopped/uninitialised
- 1 = playing or buffering sound (play has been called, waiting for data etc.)
- Note that a 1 may not always guarantee that sound is being heard, given buffering and autoPlay status.
- paused
- Boolean indicating pause status. True/False.
- Treat as read-only; use
pause()
,resume()
andtogglePause()
methods to affect state.
- readyState
- Numeric value indicating a sound's current load status
- 0 = uninitialised
- 1 = loading
- 2 = failed/error
- 3 = loaded/success
- didBeforeFinish
- Boolean indicating whether
beforeFinish()
condition was reached.
- didJustBeforeFinish
- Boolean indicating whether
justBeforeFinish()
condition was reached.
- waveformData
- Array of 256 floating-point (three decimal place) values from -1 to 1, can be used to draw a waveform while playing a sound. See Page-as-playlist demo for example implementation. Requires Flash 9+.
waveformData
is set and updated duringwhileplaying()
. A simple graph could be drawn by looping through the values and multiplying by a vertical scale value (eg. 32, which would make a graph with peaks of -32 and +32 pixels.)- Example code:
someSoundObject.whileplaying = function() { // Move 256 absolutely-positioned 1x1-pixel DIVs, for example (ugly, but works) var gPixels = document.getElementById('graphPixels').getElementsByTagName('div'); var gScale = 32; // draw -32 to +32px from "zero" (i.e., center Y-axis point) for (var i=0; i<256; i++) { graphPixels[i].style.top = (gScale+Math.ceil(this.waveformData[i]*-gScale))+'px'; } }
- SM2 implementation note:
waveformData
contains both left and right channels, and the data represents a raw sound wave rather than a frequency spectrum. - Related Adobe technical documentation (Flash 9/AS3 Sound() object): computeSpectrum()
- Note: Flash security measures may deny access to waveformData when loading MP3s from remote domains.
- Warning: This feature is experimental, and will probably eat up a lot of CPU. The amount of data passed from Flash to JS is not terribly large, but the JS-DOM updates and browser reflow can be expensive. Use with caution.
- eqData
- Array of 256 floating-point (three decimal place) values from 0 to 1, can be used to draw a spectrum (frequency range) graph while playing a sound. See Page-as-playlist demo for example implementation. Requires Flash 9+.
- A spectrum frequency graph reflects the level of frequencies being played, from left to right, low to high (i.e., 0 to 20,000 Hz.)
eqData
is set and updated duringwhileplaying()
. A simple graph could be drawn by looping through the values and multiplying by a vertical scale value (eg. 32, thus a graph with peaks of 32 pixels.)- Example code:
someSoundObject.whileplaying = function() { // Move 256 absolutely-positioned 1x1-pixel DIVs, for example (ugly, but works) var gPixels = document.getElementById('graphPixels').getElementsByTagName('div'); var gScale = 32; // draw 0 to 32px from bottom for (var i=0; i<256; i++) { graphPixels[i].style.top = (32-(gScale+Math.ceil(this.waveformData[i]*gScale)))+'px'; } }
- Related Adobe technical documentation (Flash 9/AS3 Sound() object): computeSpectrum()
- Note: Flash security measures may deny access to waveformData when loading MP3s from remote domains.
- Warning: This feature is experimental, and will probably eat up a lot of CPU. The amount of data passed from Flash to JS is not terribly large, but the JS-DOM updates and browser reflow can be expensive. Use with caution.
- peakData
- Object literal format including
left
andright
properties with floating-point values ranging from 0 to 1, indicating "peak" (volume) level. Updated duringwhileplaying()
. See Page-as-playlist demo as one example. Requires Flash 9+. - Example (within relevant sound object handler):
someSoundObject.whileplaying = function() { soundManager._writeDebug('Peaks, L/R: '+this.peakData.left+'/'+this.peakData.right); }
SMSound Methods
Functions which may be called directly on sound objects.
SMSound Object Methods
SoundManager provides wrappers for most SMSound methods - eg. soundManager.play('mySound')
checks for a valid sound object, and then calls soundManager.sounds['mySound'].play()
on that particular object.
The following methods can be called directly on a SMSound instance. The method calls are the same as the SoundManager global methods documented above for existing sound objects, minus the sound ID parameter.
- play([options object])
- setPosition(msecOffset:integer)
- pause()
- resume()
- togglePause()
- mute()
- unmute()
- setVolume(volume:integer)
- setPan(pan:integer)
- stop()
- unload()
- destruct() (called via soundManager.destroySound())
SoundManager Default Options
An optional object specifying event handlers etc., passed to createSound()
and play()
.
SoundManager Runtime Properties
Elements of SoundManager which are set at runtime, intended as read-only.
SoundManager Dynamic (Runtime) Properties
Some properties are dynamic, determined at initialisation or later during runtime, and should be treated as read-only. Currently, supported()
and features
are the only properties that fall in this category.
soundManager.features Object
As certain sound functionality is only available beginning with Flash 9, soundManager.features
can provide a consistent way of checking for feature support.
The structure (intended as read-only) is currently as follows:
soundManager.features = {
buffering: [boolean],
peakData: [boolean],
waveformData: [boolean],
eqData: [boolean],
movieStar: [boolean]
}
Example (checking for peakData
support):
if (soundManager.features.peakData) {
// do peak data-related things here
}
The features object is populated at initialisation time; the current feature support tests simply check the value of soundManager.flashVersion
being >= 9. This object has been added in anticipation of additional features with future versions of Flash.
SoundManager Core Events
Events fired by SoundManager at start-up
The following events are attached to the soundManager
global object and are useful for detecting the success/failure of the API's initialisation.
Keep in mind that these core events are effectively asynchronous (ie., they may fire long before or after window.onload()
) and therefore should not be relied on as the "ready" event for starting your application. Use the standard "DOM content loaded" or window load events for your own initialization routines.
For a more flexible queue-based, addListener-style approach to the onload event, see soundManager.onready()
.
- onerror()
- Function called when SoundManager fails to successfully initialise after Flash attempts an init call via ExternalInterface.
- Example:
soundManager.onerror = function() { alert('SoundManager failed to load'); }
- This handler should be called if there is an ExternalInterface problem or other exceptions that fire when the initialisation function is called.
- If you want multiple listeners for this event, see soundManager.onready().
- oninitmovie()
- Function called immediately after the SWF is either written to (or retrieved from) the DOM as part of the start-up process. This event can be useful if you wish to implement your own start-up time-out, eg. for handling flash blockers, start-up failures or other custom messaging.
- Example:
soundManager.oninitmovie = function(){ alert('SWF init.'); }
- onload()
- Function called when SoundManager has successfully loaded.
- Example:
soundManager.onload = function() { alert('SoundManager ready to use'); }
- Once this function has been called, all core methods will be available to use.
- Note that
onload()
is not called when SoundManager fails to load; instead,onerror()
is called. - If you want multiple listeners for this event, see soundManager.onready().
- onready(callback:function(status),[scope])
- Queue
onload()
-style event listener(s), triggered when soundManager has either started or failed. - Example:
soundManager.onready(myOnReadyHandler); soundManager.onready(myOtherHandler);
- For more detail and examples, see soundManager.onready().
SoundManager Collections
Object collections which SoundManager maintains during runtime.
SoundManager Object Collections
- soundIDs[]
- An array of sound ID strings, ordered by creation. Can be used to iterate through
sounds{}
by ID. - sounds{}
- An object literal/JSON-style instance of
SMSound
objects indexed by sound ID (as insounds['mySound']
orsounds.mySound
), used internally by SoundManager.soundManager.getSoundById()
may be used as an alternate to directly accessing this object.
Sound Options Object Format
Object Literal, JSON-style form passed to createSound()
and play()
Object Literal Format
Sounds can be created with instance-specific parameters in an object literal (JSON) format, where omitted parameters inherit default values as defined in soundManager.
soundManager.createSound({
id: 'mySound',
url: '/path/to/some.mp3',
autoLoad: true,
autoPlay: false,
onload: function() {
alert('The sound '+this.sID+' loaded!');
},
volume: 50
});
This object can also be passed as an optional argument to the play
method, overriding options set at creation time.
For a full list of available options, see Sound Properties Object
API Elements
SoundManager and SMSound API
-
SoundManager
Properties
- allowPolling
- allowFullScreen
- altURL
- consoleOnly
- debugMode
- defaultOptions
- flash9Options
- features
- flashLoadTimeout
- flashVersion
- isFullScreen
- movieStarOptions
- nullURL
- url
- useConsole
- useFastPolling
- useHighPerformance
- useMovieStar
- wmode
- waitForWindowLoad
Methods
- canPlayURL()
- createSound()
- createVideo()
- destroySound()
- destroyVideo()
- getMemoryUse()
- getSoundById()
- loadFromXML()
- mute()
- pause()
- pauseAll()
- play()
- reboot()
- resume()
- resumeAll()
- setPan()
- setPosition()
- setVolume()
- supported()
- stop()
- stopAll()
- toggleMute()
- togglePause()
- unload()
- unmute()
Events
- onerror()
- oninitmovie()
- onload()
- onready()
-
SMSound (Sound Object)
Properties (Instance Options)
- autoLoad
- autoPlay
- bufferTime
- eqData
- isMovieStar
- multiShot
- multiShotEvents
- onbeforefinishtime
- onjustbeforefinishtime
- pan
- peakData
- position
- sID
- stream
- url
- useVideo
- volume
- waveformData
Dynamic Properties
- bytesLoaded
- bytesTotal
- isBuffering
- didBeforeFinish
- didJustBeforeFinish
- duration
- durationEstimate
- loaded
- muted
- paused
- playState
- position
- readyState
Events
- onbufferchange()
- ondataerror()
- onfinish()
- onload()
- onpause()
- onplay()
- onresume()
- onstop()
- onjustbeforefinish()
- onbeforefinishcomplete()
- onbeforefinish()
- onid3()
- whileloading()
- whileplaying()
Methods
- destruct()
- mute()
- pause()
- resume()
- setPan()
- setPosition()
- setVolume()
- stop()
- toggleMute()
- togglePause()
- unload()
- unmute()