SoundManager 2: Documentation
SoundManager Configuration
Flash URLs, version + performance options
SoundManager Properties
SoundManager has properties which configure debug mode, flash movie path and other behaviours. At minimum, the soundManager.url
property must be assigned a path used to look for the necessary flash movie.
allowPolling = true; // enable flash status updates. Required for whileloading/whileplaying.
consoleOnly = false; // if console is being used, do not create/write to #soundmanager-debug
debugMode = true; // enable debugging output (div#soundmanager-debug, OR console..)
debugFlash = false; // enable debugging output inside SWF, troubleshoot Flash/browser issues
flashLoadTimeout = 1000; // ms to wait for flash movie to load before failing (0 = infinity)
flashVersion = 8; // version of flash to require, either 8 or 9. Some features require 9.
nullURL = 'about:blank'; // (Flash 8 only): URL of silent/blank MP3 for unloading/stop request.
url = '/path/to/swfs/'; // path (directory) where SM2 .SWF files will be found.
useConsole = true; // use firebug/safari console.log()-type debug console if available
useMovieStar = true; // enable Flash 9.0r115+ MPEG4 audio support
useFastPolling = false; // fast timer=higher callback frequency, combine w/useHighPerformance
flashPollingInterval = null; // Frequency for Flash. Default = 50 unless useFastPolling = true.
useHighPerformance = false;// position:fixed flash movie for faster JS/flash callbacks
waitForWindowLoad = false; // always delay soundManager.onload() until after window.onload()
wmode = 'transparent'; // null, transparent, opaque (last two allow HTML on top of flash)
allowScriptAccess = 'always'; // for scripting SWF (object/embed prop.), 'always' or 'sameDomain'
useFlashBlock = true; // better handling of SWF if load fails, let user unblock. See demo.
useHTML5Audio = false; // beta feature: Use HTML5 Audio() where supported.
To modify global SoundManager default parameters 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 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.debugFlash
soundManager.debugFlash
configures SM2's flash debugging output, disabled (false) by default. When enabled, the Flash portion of SM2 will write debug statements within the Flash movie. This can be useful for troubleshooting Flash/JS/browser (ExternalInterface) issues and so on.
A CSS class of flash_debug
will also be appended to the Flash #sm2-container
DIV element when enabled, if you wish to style it differently.
For a live example, see Flash Movie Debug Output in the Troubleshooting section.
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/swfs/';
(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) 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. If you want to handle flash block-type situations, see soundManager.useFlashBlock.
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.flashPollingInterval
Setting this will override useFastPolling
. E.g. set this to 200 to have 200ms intervals. This is useful in case your callbacks are CPU intensive.
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, 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.useFlashBlock
Flash blockers (eg. FlashBlock, "Click To Flash") can prevent the flash portion of SM2 from loading, which will cause a start-up error with a time-out.
SM2 historically has kept the flash movie off-screen and out of view, and thus the user could not click on and unblock it. Now with useFlashBlock = true
, the movie positioning can be handled by CSS. The initial state is still off-screen by default, but will change to be in view when a blocking (time-out) situation may be encountered. You can also edit the CSS to taste, of course.
When starting up, CSS classes are appended to the #sm2-container
DIV (which you can provide, or SM2 will create and append to the document.) The CSS classes change with the state of SM2's start-up, eg. #sm2-container.swf_timedout { border:1px solid red; }
could be used to highlight the movie to the user for unblocking and so on.
Setting useFlashBlock = true
will cause SM2 to wait infinitely for the Flash content to load after an initial (non-fatal) timeout, having already waited for flashLoadTimeout
to pass. If flashLoadTimeout = 0
, SM2 will immediately go into "flash block mode" on start-up.
The relevant CSS is as follows:
#sm2-container {
/* Initial state: position:absolute/off-screen, or left/top:0 */
}
#sm2-container.swf_timedout {
/* Didn't load before time-out, show to user.
Maybe highlight on-screen, red border, etc..? */
}
#sm2-container.swf_unblocked {
/* Applied if movie loads successfully
(flash started, so move off-screen etc.) */
}
#sm2-container.swf_error {
/* "Fatal" error case: SWF loaded,
but SM2 was unable to start for some reason.
(Flash security or other error case.) */
}
#sm2-container.high_performance {
/* Additional modifier for "high performance" mode
should apply position:fixed and left/bottom 0 to stay on-screen
at all times (better flash performance) */
}
#sm2-container.flash_debug {
/* Additional modifier for flash debug output mode
should use width/height 100% so you can read debug messages */
}
For a live example, see the FlashBlock Demo.
soundManager.useHTML5Audio
Warning: Beta-ish, in-progress feature; subject to bugs, API changes etc. By default, special check to enable feature for the Apple iPad 3.2+ (which does not support Flash) and Palm Pre, otherwise currently disabled by default. Works on iPhone OS 4.0 / iOS 4.0+.
Determines whether HTML5 Audio()
support is used to play sound, if available, with Flash as the fallback for playing MP3/MP4 (AAC) formats. Browser support for HTML5 Audio varies, and format support (eg. MP3, MP4/AAC, OGG, WAV) can vary by browser/platform.
The SM2 API is effectively transparent, consistent whether using Flash or HTML5 Audio()
for sound playback behind the scenes. The HTML5 Audio API is roughly equivalent to the Flash 8 feature set, minus ID3 tag support and a few other items. (Flash 9 features like waveform data etc. are not available.)
SoundManager 2 + useHTML5Audio: Init Process
At DOM ready (if useHTML5Audio = true), a test for Audio()
is done followed by a series of canPlayType()
tests to see if MP3, MP4, WAV and OGG formats are supported. If none of the "required" formats (MP3 + MP4, by default) are supported natively, then Flash is also added as a requirement for SM2 to start.
soundManager.audioFormats
currently defines the list of formats to check (MP3, MP4 and so on), their possible canPlayType()
strings (long story short, it's complicated) and whether or not they are "required" - that is, whether Flash should be loaded if they don't work under HTML5. (Again, only MP3 + MP4 are supported by Flash.) If you had a page solely using OGG, you could make MP3/MP4 non-required, but many browsers would not play them inline.
SM2 will indicate its state (HTML 5 support or not, using Flash or not) in console.log()
-style debug output messages when debugMode = true
.
"My browser does HTML5, why not MP3"?
Despite best efforts, some browsers eg. Chrome on Windows may only return "maybe" for Audio().canPlayType('audio/mpeg; codecs=mp3')
and variants; by default, SoundManager 2 will only assume a format is supported if a "probably" response is given. You can modify soundManager.html5Test
to something like /(probably|maybe)/i
if you want to be a bit riskier, but you should consider potential false positives.
At this time, only Safari and Chrome (excluding Chromium?) support MP3 and MP4 formats. Other browsers have excluded them because MP3 and MP4 are not "free" formats. For these cases, Flash is used as the fallback support for MP3/MP4 as needed.
Bonus HTML5 formats: OGG, WAV
WAVe (an old standard) and OGG (a MP3-like codec, except free) are both supported in a majority of browsers via HTML5, so SoundManager 2 will also test for support for these formats. A Flash fallback for these formats has not been implemented.
Testing audio format support
Once soundManager.onready()
has fired and SM2 has started, you can check for support via a number of methods. Namely, soundManager.canPlayLink() will take an <a>
element and check its href
and type
attributes, if available, for hints as to its format or type. You can also pass arbitrary URLs to soundManager.canPlayURL(), which will make a "best guess" based on the extension it finds. In any event, SM2 will return a true/false value from canPlay methods based on HTML and/or flash capabilities.
To see what formats are supported by HTML5, watch SM2's debug/console output when debug is enabled, or dump the contents of soundManager.html5
to the console; it will show the results of tests for simple items like "mp3", as well as canPlayType()
strings such as 'mpeg; codecs=mp3'
Apple iPad, iPhone, Palm Pre: Special Cases
The "Big iPhone" doesn't do Flash, and does support HTML5 Audio()
pretty decently - so SM2 makes a special exception to enable useHTML5Audio
when it detects an iPad, iPhone or Palm Pre user agent string by default. Feel free to disable this if you wish.
iPad and iPhone require user interaction to start a sound, eg. the createSound() and play() call should happen within an onclick() handler on a link, etc. The "security" model here seems to be implemented similarly to the way pop-up blockers work. You may "chain" sounds (eg. create and play a new one) provided it is done via the onfinish() event of a sound initiated by a user, however. The Muxtape-style demo on the SM2 homepage uses this, and will advance the playlist on the iPad/iPhone if allowed.
iPad 3.2 gets hung up on the "BC quail" HE-AAC example sound for some reason, and endlessly loops it rather than finishing and moving on to the next item. May be an iPad playback bug, as other formats are fine. iPhone OS 4 (iOS 4) does not show this issue.
iPhone OS version < 3.1 doesn't work, but 3.1 (and possibly earlier versions, not verified) have a native Audio()
object. However, they seem to simply not play sound when play()
is called, so SM2 looks for and ignores the iPhone with these OS revisions.
The Palm Pre supports a number of MP3, MP4 and WAV formats (WebOS 1.4.1 was tested; it didn't seem to like MP3s at 192kbps, but 128kbps was fine.)
HTML5 Audio: Notes, bugs, quirks and annoyances
As of the V2.97.20110424 release of SM2:
- HTML5 audio in Safari on Snow Leopard 10.6.3 through 10.6.9 (10.6.7 was released 03/2011) are blacklisted and will fall back to Flash. 10.6.8 and 10.6.9 are preemptive guesses. According to beta testers, OS X 10.7 ("Lion") has fixed the intermittent HTML5 audio load/playback issue.
new Audio(null)
is no longer used for iOS, as iOS would attempt to load a URL called "null".- iOS 4.2 or 4.3 may have introduced new security restrictions around
onfinish()
->unload()
->play()
that prevents the "play-through" behaviour previously allowed in certain cases. Theunload()
attempts to nullify the audio'ssrc
attribute, breaking the futureplay()
request. The Muxtape/button/link demos were affected by this, and have been fixed with this release. To prevent this issue in your own apps, avoidunload()
and simply useonfinish()
->play()
for iOS.
As of the V2.97.20110306 release of SM2:
- Testing suggests that auto-play ("auto-annoy?") does work on iOS 4.1, but are aggressively blocked as of iOS 4.2.
_resetProperties()
when setting Audio().src, fix sound1.play() -> sound2.play() -> sound1.play() case on iOS 4.1 not correctly re-assigning original sound URL (related to global audio object.)- If no flash is detected, try forcing
useHTML5Audio = true
(eg. desktop safari on new Macs which don't come with Flash.) Related: flash detection code tweak. - isNaN() check for HTML5 loading (saw one under Safari, in testing).
- Use new Audio(null) vs (), Opera 9.64 expects URL argument; throws WRONG_ARGUMENTS_ERR otherwise. Doesn't implement canPlayType() either, but both are fixed in future releases.
As of the V2.97.20110123 release of SM2:
New (experimental)
soundManager.useGlobalHTML5Audio
attribute, enabled by default for mobile + iOS. Enables use of a single audio object, re-used for loading and playing all sounds. iOS currently can only play one sound at a time, so this limitation is safe for now. The global object fixes previous regression of play-through/playNext()-style behaviours.Sound recycling with new global audio feature should work better than in prior (development) versions.
Improved broken Safari/Snow Leopard HTML5 audio situation: HTML5 mode is no longer disabled - and if available, Flash is used to play MP3/MP4 content to work around known playback issues with native HTML5 audio.
New (experimental)
soundManager.requireFlash
property (default: false.) If true, prevents HTML5-only mode on devices with both HTML5 and Flash. May be useful when HTML5 is enabled (and can play MP3), but Flash is desired to play RTMP content etc. As of this version, will only use Flash for RTMP.Fix for
type:'audio/mp3'
returning false oncanPlay()
. Timer update-while-paused tweak.More event listeners, ignore events on destroyed sounds, improved event clean-up, "seek before load" fix
As of the January 1, 2011 (V2.97a.20110101) and December, 2010 releases of SM2 (V2.97a.20101221):
The
bytesLoaded
andbytesTotal
properties may become less-relevant under HTML5 due to non-linear HTTP downloading (using ranges and partials), but they are still provided under Firefox at this time.Related to bytes loading/total, a sound's
onload
event may not always be fired (Mozilla currently discourage use of the DOMloaded
event), again because of range requests and the ability to arbitrarily seek within a file.Basic support for the W3
TimeRanges
implementation of sound buffering (ie., loaded data) has been implemented. This gives an idea of "total time loaded", but again, is not necessarily sequential.HTML5 audio is disabled for all versions of Safari (4 and 5) on Snow Leopard (OS X 10.6.3 - 10.6.5) until Apple fixes issues with audio loading and playback due to bugs in "underlying frameworks." See Webkit #32159. HTML5 audio in Safari on Windows (provided QuickTime is installed) does not have the same fatal bug.
As of the October, 2010 release of SM2 (V2.97a.20101010):
HTML5 audio is disabled for all versions of Safari (4 and 5) on Snow Leopard (OS X 10.6.3 and 10.6.4) until Apple fixes issues with audio loading and playback due to bugs in "underlying frameworks." See Webkit #32159.
As of the August, 2010 release of SM2 (V2.96a.20100822):
Safari 5.0.1 (533.17.18) on Snow Leopard (10.6.x) continues to show buggy HTML5 audio load/playback behaviour. Apple are aware of the regression, which began with Safari 4.0 on Snow Leopard (perhaps with the new QuickTime.) See Webkit #32159.
iPad/iPhone iOS4 will now play a sequence of sounds if using
onfinish()
to create/start the next (eg., the Muxtape-style playlist on the SM2 homepage will play through once the user starts it.) In any event, user interaction is always required to start the first sound.
As of the June, 2010 release of SM2 (V2.96a.20100624):
Safari 5.0 (533.16) on OS X Snow Leopard (10.6.x) continues to show buggy HTML5 audio load/playback behaviour, same as with Safari 4.0.5 on Snow Leopard only - may be related to underlying QuickTime implementation (a guess, at this point.) SM2 will disable HTML5 audio support by default for this specific browser + OS combo. See Webkit #32159 for discussion + testcases.
As of the May, 2010 release of SM2 (V2.96a.20100520):
Safari 4.0.5 on OS X Snow Leopard (10.6.x) appears to have an annoying bug where audio inconsistently fails to load / play; SM2 will currently disable or ignore the HTML5 feature on this exact browser + OS version. See Webkit #32159 for discussion + testcases. Note that Safari on OS X 10.5 "Leopard" and on Windows do not appear to have this bug; it seems to be limited to Snow Leopard, seen on OS X 10.6.3.
Some browsers (and iPad 3.2?) do not fire
progress
events, and/or do not implement bytesLoaded/bytesTotal-style attributes.iPad 3.2 appears to be able to only play one sound at a time, and will terminate other sounds.
iPad 3.2 may also loop AAC+ (HE-AAC) and WAV sounds, perhaps not firing onfinish() and resetting the position to 0 each time, but is fine with MP3s. This has been observed, but not fully-tested.
Looping in HTML5 is either "infinite" or "none". A wrapper may be created for SM2 so that a number of loops can be specified, as with Flash. This is not yet implemented.
Panning (left/right channel balance) does not appear to be in HTML5.
Flash-only features such as ID3 tag reading, waveform and spectrum data will simply be ignored, and their related events will not fire on SMSound objects which are using HTML5.
General Disclaimer
HTML5 audio support may still be in flux, and may not be fully-supported or implemented consistently in modern browsers. Be careful out there.
Related Reading on HTML5
For some more backstory on HTML and audio, see the 24ways.org article "Probably, Maybe, No": The State Of HTML5 Audio (published December, 2010.)
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 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 canPlayLink(<a>:DOM element)
- Normalized method which checks
canPlayMIME()
andcanPlayURL()
as needed to estimate the playability of an HTML link; this means both thehref
andtype
attributes, if provided, are checked for matching file extension and/or MIME type patterns. - Example:
/* example links: <a id="song1" href="/music/player.php?songID=1" type="audio/mp3">play song 1</a> // type match <a id="song2" href="song2.mp3">play song 2</a> // URL match */ var aLink = document.getElementById('mySong'); if (soundManager.canPlayLink(aLink)) { soundManager.play('mySongSound',aLink.href); }
- canPlay:boolean canPlayMIME(MIMEtype:string)
- Returns a boolean indicating whether soundManager can play the given MIME type - eg.,
audio/mp3
. The types supported vary based on Flash version and MPEG4 (MovieStar mode) options. -
MIME type patterns are as follows:
- Defaults:
/^audio\/(?:x-)?(?:mp(?:eg|3))\s*;?/i;
- eg.audio/mp3
oraudio/mpeg
- MovieStar-only formats:
/^audio\/(?:x-)?(?:mp(?:eg|3)|mp4a-latm|aac|speex)\s*;?/i;
- eg.audio/m4a or audio/aac
- Defaults:
- Example:
// link example: <a id="song1" href="foo.php?songID=1" type="audio/mp3">play song 1</a> var aLink = document.getElementById('song1'); if (soundManager.canPlayLink(aLink)) { soundManager.play('song1Sound',aLink.href); }
- If no
type
attribute is found, this method will returnnull
instead offalse
.
- 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); }
- If no
href
attribute is found, this method will returnnull
instead offalse
.
- object:SMSound createSound(object:options)
- Creates a sound with an arbitrary number of optional arguments. Returns a
SMSound
object instance. Requiresid
andurl
at a minimum. -
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.
- If
createSound
is called with the ID of an existing sound, that sound object will be returned "as-is". Any othercreateSound
options passed (eg.,url
orvolume
, etc.) will be ignored.
- object:SMSound createSound(id:string, url:string) - overloaded method
- Creates a sound with the specified ID and URL (simple two-parameter method.)
- Example:
soundManager.createSound('mySound','/audio/mysoundfile.mp3');
- destroySound(id:string)
- Stops, unloads and destroys a sound specified by ID.
- Example:
soundManager.destroySound('mySound');
- SMSound equivalent example:
mySound.destruct();
- object:SMSound mute([id:string])
- Mutes the sound specified by ID and returns that sound object. If no ID specified, all sounds will be muted and null is returned. Affects muted property (boolean.)
- Example:
soundManager.mute('mySound');
- onready(callback:function, [scope])
- Queues an event callback/handler for successful initialization and "ready to use" state of SoundManager 2. An optional scope parameter can be specified; if none, the callback is scoped to the window. If
onready()
is called after successful initialization, the callback will be executed immediately. Theonready()
queue is processed beforesoundManager.onload()
. - Example:
soundManager.onready(function() { alert('Yay, SM2 loaded OK!'); });
- Queueing multiple handlers:
soundManager.onready(myOnReadyHandler); soundManager.onready(myOtherHandler);
- 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.
- ontimeout(callback:function, [scope])
- Queues an event callback/handler for SM2 init failure, processed at (or immediately, if added after) SM2 initialization has failed, just before
soundManager.onerror()
is called. An optional scope parameter can be specified; if none, the callback is scoped to the window. - Example:
soundManager.ontimeout(function() { alert('SM2 failed to start. Flash missing, blocked or security error?'); });
- Queueing multiple handlers:
soundManager.ontimeout(myOnTimeoutHandler); soundManager.ontimeout(myOtherHandler);
- The timeout event is not necessarily fatal, as SM2 may be rebooted and fire an
onready()
in theuseFlashBlock
case (where the user sees, and chooses to unblock, the Flash component after a failed init attempt.) - 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.
- object:SMSound play(id:string, [options object])
- Starts playing the sound specified by ID. (Will start loading if applicable, and will play ASAP.)
- Returns an
SMSound
(sound object) instance. - 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});
- object:SMSound pause(id:string)
- Pauses the sound specified by ID. Does not toggle. Affects paused property (boolean.) Returns the given sound object.
- Example:
soundManager.pause('mySound');
- pauseAll()
- Pauses all sounds whose playState is >0. Affects paused property (boolean.)
- Example:
soundManager.pauseAll();
- 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.
- object:SMSound resume(id:string)
- Resumes and returns the currently-paused sound specified by ID.
- Example:
soundManager.resume('mySound');
- resumeAll()
- Resumes all currently-paused sounds.
- Example:
soundManager.resumeAll();
- object:SMSound setPan(id:string,volume:integer)
- Sets the stereo pan (left/right bias) of the sound specified by ID, and returns the related sound object. Accepted values: -100 to 100 (L/R, 0 = center.) Affects pan property.
- Example:
soundManager.setPan('mySound',-80);
- object:SMSound setPosition(id:string,msecOffset:integer)
- Seeeks to a given position within a sound, specified by miliseconds (1000 msec = 1 second) and returns the related sound object. Affects position property.
- Example:
soundManager.setPosition('mySound',2500);
- Can only seek within loaded sound data, as defined by the duration property.
- object:SMSound setVolume(id:string, volume:integer)
- Sets the volume of the sound specified by ID and returns the related sound object. Accepted values: 0-100. Affects volume property.
- Example:
soundManager.setVolume('mySound',50);
- object:SMSound stop(id:string)
- Stops playing the sound specified by ID. Returns the related sound object.
- Example:
soundManager.stop('mySound');
- stopAll()
- Stops any currently-playing sounds.
- Example:
soundManager.stopAll();
- object:SMSound toggleMute(id:string)
- Mutes/unmutes the sound specified by ID. Returns the related sound object.
- Example:
soundManager.toggleMute('mySound');
- object:SMSound togglePause(id:string)
- Pauses/resumes play on the sound specified by ID. Returns the related sound object.
- Example:
soundManager.togglePause('mySound');
- object:SMSound unload(id:string)
- Stops loading the sound specified by ID, canceling any current HTTP request. Returns the related sound object.
- 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.
- object:SMSound unmute([id:string])
- Unmutes the sound specified by ID. If no ID specified, all sounds will be unmuted. Affects muted property (boolean.) Returns the related sound object.
- Example:
soundManager.unmute('mySound');
- object:SMSound load(id:string, [options object])
- Starts loading the sound specified by ID, with options if specified. Returns the related sound object.
- Example:
soundManager.load('mySound');
- Example 2:
soundManager.load('mySound',{volume:50,onfinish:playNextSound});
- object:SMSound getSoundById(id:string)
- Returns an
SMSound
object specified by ID, or null if a sound with that ID is not found. - 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
- isSupported:boolean ok() ( previous name: 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, and is useful when you want to create or play a sound without knowing SM2's current state.
- Example:
var isSupported = soundManager.ok();
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. Note that most methods will return the sound object instance, allowing for method chaining if desired.
- destruct()
- Stops, unloads and destroys a sound, freeing resources etc.
- Example:
mySound.destruct();
- object:SMSound load([options object])
- Starts loading the given sound, with options if specified.
- Example:
mySound.load();
- Example 2:
mySound.load({volume:50,onfinish:playNextSound});
- object:SMSound mute()
- Mutes the given sound. Affects muted property.
- Example:
mySound.mute();
- object:SMSound onposition(msecOffset:integer, callback:function, [scope])
- Registers an event listener, fired when a sound reaches or passes a certain position while playing. Position being "listened" for is passed back to event handler. Will also fire if a sound is "rewound" (eg. via
setPosition()
to an earlier point) and the given position is reached again. Listeners will be removed if a sound is unloaded. An optional scope can be passed as well. - Note that for
multiShot
cases, only the first play instance'sposition
is tracked in Flash; therefore, subsequent "shots" will not have onposition() events being fired. - Example:
mySound.onposition(3000, function(eventPosition){console.log(this.sID+' reached '+eventPosition});
- object:SMSound pause()
- Pauses the given sound. (Does not toggle.) Affects paused property (boolean.)
- Example:
mySound.pause();
- object:SMSound 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});
- object:SMSound setPosition(msecOffset:integer)
- Seeks 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.
- object:SMSound resume()
- Resumes the currently-paused sound. Does not affect currently-playing sounds.
- Example:
mySound.resume();
- object:SMSound 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);
- object:SMSound setVolume(volume:integer)
- Sets the volume of the given sound. Accepted values: 0-100. Affects volume property.
- Example:
mySound.setVolume(50);
- object:SMSound toggleMute()
- Mutes/unmutes the given sound. Affected muted property (boolean.)
- Example:
mySound.toggleMute();
- object:SMSound togglePause()
- Pauses/resumes play of the given sound. Will also start a sound if it is has not yet been played.
- Example:
mySound.togglePause();
- object:SMSound stop()
- Stops playing the given sound.
- Example:
mySound.stop();
- object:SMSound 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.
- object:SMSound unmute()
- Unmutes the given sound. Affects muted property.
- Example:
mySound.unmute();
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 onload
-like events. Handlers cannot be "directly" assigned (eg. someSound.onload), but can be passed as option parameters to several sound methods.
soundManager.play('mySound',{
onfinish: function() {
alert('The sound '+this.sID+' finished playing.');
}
});
Event handlers are scoped to the relevant sound object, so 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.
- 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()
.
- 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.
- onconnect()
- Fires when a sound using an RTMP
serverURL
property has attempted to connect, and has either succeeded or failed. Affectsconnected
property. Once connected, a stream can be requested from the RTMP server. - Example:
var s = soundManager.createSound({ id: 'rtmpTest', serverURL: 'rtmp://localhost/test/', url: 'song.mp3', onconnect: function(bConnect) { // this.connected can also be used soundManager._writeDebug(this.sID+' connected: '+(bConnect?'true':'false')); } }).play(); // will result in connection being made
- 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.
- 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.
- 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.)
- 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].)
- onpause()
- Fires when a sound pauses, eg. via
sound.pause()
. - Example:
soundManager.pause('mySound');
- onplay()
- Fires when
sound.play()
is called.
- 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.
- 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.
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, typically over HTTP. Can be referenced as
this.url
from within sound object event handlers such asonload()
orwhileplaying()
, etc.
- serverURL
- Note: Experimental feature. Only for use with RTMP streaming, ie., Flash Media Server and similar servers.
- The RTMP server address which Flash will connect to using a NetStream object. Only the server address is specified here, when RTMP is in use; the
url
property is used to point to a specific resource on the server. - Example:
soundManager.createSound({ id: 'mySound', serverURL: 'rtmp://localhost/rtmpDemo/', // RTMP server url: 'mysong.mp3' // path to stream }).play();
- usePolicyFile
- Boolean value (default:
false
) which instructs Flash, when loading MP3/MP4 content from remote/third party domains, to request example.com/crossdomain.xml first in order to determine permissions for access to metadata such as ID3 info, waveform, peak and/or spectrum data. usePolicyFile
will be automagically set totrue
if your sound options have anonid3()
event handler, or uses sound data (peak/wave/spectrum) features. By default, Flash will not have access to this metadata on remote domains unless granted cross-domain security permissions via the crossdomain.xml file.- Consider additional HTTP traffic (albeit, perhaps with caching-like behaviour for subsequent checks?) and silent 404s in most cases given few hosts use crossdomain.xml files.
- See Adobe's knowledge base for related ID3 + crossdomain.xml documentation.
Sound Object Dynamic Properties
Each sound includes a number of properties that are updated throughout the life of a sound - while loading or playing, for example. Many of these properties have related events that fire when they are updated, and should be treated as read-only.
- bytesLoaded
- The number of bytes currently received while loading a sound.
- bytesTotal
- The total number of bytes to be downloaded, while loading a sound.
- didBeforeFinish
- Boolean indicating whether
beforeFinish()
condition was reached.
- didJustBeforeFinish
- Boolean indicating whether
justBeforeFinish()
condition was reached.
- 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.
- eqData = {left:[], right: []}
- Object containing two arrays of 256 floating-point (three decimal place) values from 0 to 1, the result of an FFT on the waveform data. 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.left[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 can eat up a lot of CPU in some cases. 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.
- Backward compatibility note: Up to SoundManager 2.95a.20090717, eqData was a single array containing one channel of data. In newer versions this is unchanged, except the array now has .left[] and .right[] objects attached to it. To ensure future compatibility, use eqData.left[0] instead of eqData[0] and so on.
- id3
- An object literal populated, if applicable, when ID3 data is received (related handler:
onid3()
) - For property details, see onid3().
- 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.
- connected
- Boolean value reflecting the state of an RTMP server connection (when
serverURL
is used to connect to a Flash Media Server or similar RTMP service.) Calls toload
orplay
will result in a connection attempt being made, andonconnect()
ultimately being called. - For example code using
connected
, see onconnect().
- 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.
- paused
- Boolean indicating pause status. True/False.
- Treat as read-only; use
pause()
,resume()
andtogglePause()
methods to affect state.
- peakData = {left:0.0, right:0.0}
- 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); }
- 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.
- position
- The current location of the "play head" within the sound, specified in milliseconds (1 sec = 1000 msec).
- readyState
- Numeric value indicating a sound's current load status
- 0 = uninitialised
- 1 = loading
- 2 = failed/error
- 3 = loaded/success
- type
- A MIME type-like string eg.
audio/mp3
, used as a hint for SM2 to determine playability of a link with methods likecanPlayURL()
. - This can be helpful when you have a sound URL that does not have an .mp3 extension, but serves MP3 data (eg., a PHP or other CGI script.)
- Example:
var s = soundManager.createSound({ id: 'aSound', url: '/path/to/some.php?songID=123', type: 'audio/mp3' // indicates an MP3 link, so SM2 can handle it appropriately });
- waveformData = {left:[], right:[]}
- 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.left[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 can eat up a lot of CPU in some cases. 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.
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; thus, it is the same as var sound = soundManager.getSoundById('mySound'); mySound.play();
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.
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, ok()
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 successfully started. - 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
- allowScriptAccess
- altURL
- consoleOnly
- debugFlash
- debugMode
- defaultOptions
- flash9Options
- features
- flashLoadTimeout
- flashVersion
- movieStarOptions
- nullURL
- url
- useConsole
- useFastPolling
- flashPollingInterval
- useFlashBlock
- useHighPerformance
- useHTML5Audio
- useMovieStar
- wmode
- waitForWindowLoad
Methods
- canPlayLink()
- canPlayMIME()
- canPlayURL()
- createSound()
- destroySound()
- getMemoryUse()
- getSoundById()
- load()
- mute()
- ok()
- pause()
- pauseAll()
- play()
- reboot()
- resume()
- resumeAll()
- setPan()
- setPosition()
- setVolume()
- supported()
- stop()
- stopAll()
- toggleMute()
- togglePause()
- unload()
- unmute()
Events
-
SMSound (Sound Object)
Properties (Instance Options)
- autoLoad
- autoPlay
- bufferTime
- eqData
- isMovieStar
- loops
- multiShot
- multiShotEvents
- onbeforefinishtime
- onjustbeforefinishtime
- pan
- peakData
- position
- serverURL
- sID
- stream
- type
- url
- usePolicyFile
- volume
- waveformData
Dynamic Properties
- bytesLoaded
- bytesTotal
- isBuffering
- connected
- didBeforeFinish
- didJustBeforeFinish
- duration
- durationEstimate
- loaded
- muted
- paused
- playState
- position
- readyState
Events
- onbufferchange()
- onconnect()
- ondataerror()
- onfinish()
- onload()
- onpause()
- onplay()
- onposition()
- onresume()
- onstop()
- onbeforefinishcomplete()
- onbeforefinish()
- onjustbeforefinish()
- onid3()
- whileloading()
- whileplaying()
Methods