SoundManager 2: Documentation
API Elements
SoundManager and SMSound API
-
SoundManager
Properties
- allowScriptAccess
- altURL
- audioFormats
- bgColor
- consoleOnly
- debugFlash
- debugMode
- defaultOptions
- flash9Options
- features
- flashLoadTimeout
- flashPollingInterval
- flashVersion
- forceUseGlobalHTML5Audio
- html5Only
- html5PollingInterval
- ignoreMobileRestrictions
- movieStarOptions
- preferFlash
- url
- useConsole
- useFastPolling
- useFlashBlock
- useHighPerformance
- useHTML5Audio
- wmode
- waitForWindowLoad
Methods
- canPlayLink()
- canPlayMIME()
- canPlayURL()
- clearOnPosition()
- createSound()
- destroySound()
- getMemoryUse()
- getSoundById()
- load()
- mute()
- ok()
- onPosition()
- pause()
- pauseAll()
- play()
- reboot()
- reset()
- resume()
- resumeAll()
- setup()
- setPan()
- setPlaybackRate()
- setPosition()
- setVolume()
- supported()
- stop()
- stopAll()
- toggleMute()
- togglePause()
- unload()
- unmute()
Events (Callbacks)
-
SMSound (Sound Object)
Parameters (Instance Options)
- autoLoad
- autoPlay
- bufferTime
- eqData
- from
- id
- isMovieStar
- loops
- multiShot
- multiShotEvents
- pan
- peakData
- playbackRate
- position
- serverURL
- stream
- to
- type
- url
- usePolicyFile
- volume
- waveformData
Dynamic Properties
- buffered
- bytesLoaded
- bytesTotal
- isBuffering
- connected
- duration
- durationEstimate
- isHTML5
- loaded
- muted
- paused
- playState
- position
- readyState
Events
- onbufferchange
- onconnect
- ondataerror
- onerror
- onfinish
- onload
- onpause
- onplay
- onresume
- onsuspend
- onstop
- onid3
- whileloading
- whileplaying
Methods
SoundManager Properties: soundManager.setup()
Just getting started? See the basics. For nicely-formatted, annotated source code, see the pretty-printed version.
The soundManager object has many configurable properties which set debug mode, determine the flash movie path and other behaviours.
When configuring soundManager for your use, soundManager.setup()
is the method used to assign these options; for example, soundManager.setup({ url: '/path/to/swfs/', flashVersion: 9 });
You should call the setup method before "DOM Ready", which is when SM2 applies configuration and starts up.
Below are the default settings for SoundManager 2, which are appropriate for the majority of use cases - you shouldn't need to change them. These parameters are defined and stored in soundManager.setupOptions
.
Note: The only property requiring customization is url
- this defines the path used to look for the appropriate flash SWF for driving audio when HTML5 is not available. (If not specified, the current working path is used.) Aside from flash-specific items like url
and flashVersion
, most properties can be set after "DOM Ready" without issue.
-
url: '/path/to/swf-files/',// the directory where SM2 can find the flash movies (soundmanager2.swf, soundmanager2_flash9.swf and debug versions etc.) Note that SM2 will append the correct SWF file name, depending on flashVersion and debugMode settings.
-
allowScriptAccess: 'always',// for scripting the SWF (object/embed property), 'always' or 'sameDomain'
-
bgColor: '#ffffff',// SWF background color. N/A when wmode = 'transparent'
-
consoleOnly: true,// if console is being used, do not create/write to #soundmanager-debug
-
debugMode: true,// enable debugging output (console.log() with HTML fallback)
-
debugFlash: false,// enable debugging output inside SWF, troubleshoot Flash/browser issues
-
flashVersion: 8,// flash build to use (8 or 9.) Some API features require 9.
-
flashPollingInterval: null,// msec affecting whileplaying/loading callback frequency. If null, default of 50 msec is used.
-
forceUseGlobalHTML5Audio: false,// if true, a single Audio() object is used for all sounds - and only one can play at a time.
-
html5PollingInterval: null,// msec affecting whileplaying/loading callback frequency. If null, native HTML5 update events are used.
-
html5Test: /^(probably|maybe)$/i,// HTML5 Audio() format support test. Use /^probably$/i; if you want to be more conservative.
-
flashLoadTimeout: 1000,// msec to wait for flash movie to load before failing (0 = infinity)
-
idPrefix: 'sound',// if an id is not provided to createSound(), this prefix is used for generated IDs - 'sound0', 'sound1' etc.
-
ignoreMobileRestrictions: false,// if true, SM2 will not apply global HTML5 audio rules to mobile UAs. iOS > 7 and WebViews may allow multiple Audio() instances.
-
noSWFCache: false,// if true, appends ?ts={date} to break aggressive SWF caching.
-
preferFlash: true,// overrides useHTML5audio. if true and flash support present, will try to use flash for MP3/MP4 as needed. Useful if HTML5 audio support is quirky.
-
useConsole: true,// use console.log() if available (otherwise, writes to #soundmanager-debug element)
-
useFlashBlock: false,// requires flashblock.css, see demos - allow recovery from flash blockers. Wait indefinitely and apply timeout CSS to SWF, if applicable.
-
useHighPerformance: false,// position:fixed flash movie can help increase js/flash speed, minimize lag
-
useHTML5Audio: true,// use HTML5 Audio() where supported. Some browsers may not support "non-free" MP3/MP4/AAC codecs. Ideally, transparent vs. Flash API where possible.
-
waitForWindowLoad: false,// force SM2 to wait for window.onload() before trying to call soundManager.onready()
-
wmode: null// flash rendering mode - null, 'transparent', or 'opaque' (last two allow z-index)
Legacy support note: The new approach defines top-level properties in soundManager.setupOptions
. The old approach was to assign properties directly to the soundManager instance. Thus, when soundManager.setup({ url: ... });
is called, the updated property value is assigned to both soundManager.setupOptions.url
and soundManager.url
. You can assign soundManager.url
directly as with the old method, but it is recommended to use the new setup()
-based method for forward compatibility.
Bonus: Extended soundManager.setup() Parameters
As it is common to configure soundManager properties and related events all at once, you can also pass onready
and ontimeout
parameters which will be called as if you had used soundManager.onready()
and soundManager.ontimeout()
.
You can also provide values from the following top-level soundManager properties:
defaultOptions: {...}
(global defaults for new sound objects)flash9Options: {...}
(API feature options specific to Flash 9)movieStarOptions: {...}
(Flash 9-only NetStream/RTMP-specific options)
soundManager.setup({
url: '/path/to/swfs/',
flashVersion: 9,
preferFlash: false, // prefer 100% HTML5 mode, where both supported
onready: function() {
// console.log('SM2 ready!');
},
ontimeout: function() {
// console.log('SM2 init failed!');
},
defaultOptions: {
// set global default volume for all sound objects
volume: 33
}
});
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.
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.
flashVersion
SoundManager 2 started with a Flash 8 base requirement, but can also use Flash 9 and take advantages of some unique features Flash 9 offers. By default Flash 8 will be used, but the version can be easily changed by setting flashVersion
appropriately.
Example: soundManager.setup({ 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.
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
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.
flashPollingInterval
Setting this will override useFastPolling
, and defines the interval of the internal flash timer used for callbacks to sound events like whileloading()
and whileplaying()
. For example, set this to 200 to have 200ms intervals. This is useful in the case where your callbacks are CPU intensive, or you simply wish to throttle your calls to be more CPU-conservative.
forceUseGlobalHTML5Audio
By default, SoundManager 2 only applies the "singleton"-style, single HTML5 Audio()
object for mobile devices like iOS, Android and the like. If you want to force it for desktop browsers, you can set forceUseGlobalHTML5Audio
to true
.
Example: soundManager.setup({ forceUseGlobalHTML5Audio: true });
html5PollingInterval
Setting this will enable a single interval that will affect the frequency of event callbacks such whileplaying()
for HTML5 sounds, with the exclusion of mobile devices. If null, native HTML5 update events are used. The frequency of native events may vary widely across browsers, and may exceed 500 msec on mobile and other resource-limited devices.
By default, Flash uses a 50-msec timer interval and this is a reasonable value to apply to html5PollingInterval
for desktop use cases.
ignoreMobileRestrictions
By default, SoundManager 2 only applies the "singleton"-style, single HTML5 Audio()
object for mobile devices like iOS, Android and the like. This is because most iOS devices only like playing a single Audio()
audio object at a time.
If you want to avoid applying this to it for desktop browsers, you can set ignoreMobileRestrictions
to true
.
Example: soundManager.setup({ ignoreMobileRestrictions: true });
preferFlash
This property handles "mixed-mode" HTML5 + flash cases, and may prevent 100% HTML5 mode when enabled depending on the configuration of soundManager.audioFormats. In the event HTML5 supports the default "required" formats (presently MP3), and preferFlash
is true (and flash is installed), flash will be used for MP3/MP4 content while allowing HTML5 to play OGG, WAV and other supported formats.
Important note: Because HTML5 audio has some bugs across various browsers and operating systems, preferFlash
is true
by default to help ensure MP3/MP4 play consistently. If set to false
or flash is not available, "HTML5-only" mode will kick in and will apply to all formats.
To encourage 100% HTML5 mode, call soundMangager.setup({ preferFlash: false })
and then Flash will not be used for MP3/MP4 playback, provided that HTML5 supports them.
url
soundManager.url
, applied via soundManager.setup()
, specifies the "online", generally HTTP-based path which SM2 will load .SWF movies from. The "local" (current) path of ./
will be used by default. The appropriate .SWF required (depending on the desired Flash version) will be appended to the URL.
Example: soundManager.setup({ url: '/path/to/swf-directory/' });
(Note trailing slash)
For a simple demo of this in action, see the basic template.
For cases where SM2 is being used "offline" in non-HTTP cases (eg., development environments), see altURL
.
useFastPolling
By default useFastPolling = false
, and thus SoundManager uses a 50-millisecond 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 10-msec timer is used and callback frequency may noticeably increase. This is best combined with useHighPerformance
for optimal results.
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/default 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.
* (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.
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, useHighPerformance
is disabled. When enabled, it may noticeably reduce JS/flash lag and increase the frequency of callbacks such as whileplaying()
in some circumstances.
soundManager.setup({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.
useHTML5Audio
HTML5 support is in active development. See Revision History for the latest updates on HTML5 playback support.
useHTML5Audio
determines whether HTML5 Audio()
support is used (as available) to play sound, with flash as the fallback for playing MP3 and 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 in HTML5 mode.)
By default, "100% HTML5 mode" applies to Apple iPad 3.2+ (iPad version 1.0), iPhone / iOS 4.0+ devices and others without flash. In other cases, HTML5 support is tested and if MP3/MP4 aren't natively supported, flash will be used as a backup method of playing these "required" formats. (It is assumed MP3 playback is required by default, but this is user-configurable via soundManager.audioFormats
.) HTML5 may also enable support for additional formats such as OGG and WAV.
On the desktop and other devices with flash support, SM2 will still try for 100% HTML5 mode by default. However, you can use soundManager.setup({ preferFlash: true })
if you would like to have Flash play MP3 and MP4 (AAC) formats even when they are supported via HTML5.
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 any of the "required" formats (by default, MP3) are not supported via HTML5, or if preferFlash
= true
and MP3 or MP4 are required, then flash is also added as a requirement for SM2 to start.
soundManager.audioFormats
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 do not play OGG files natively.
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; SoundManager 2 will presently assume a format is supported if a "probably" or "maybe" response is given. You can modify html5Test
to be /probably/i
if you want to be more strict, for example.
Safari, IE 9, and Chrome (excluding Chromium?) support the "non-free" MP3 and MP4 (including AAC) formats. Firefox, in some cases, does support the MP3 codec where the underlying OS has support for it. This includes Windows Vista (and newer), and as of November 2013, Firefox Aurora (development builds) also on OS X.
For the cases where MP3 is not supported via HTML5, flash is used as the fallback support for MP3/MP4 as needed. Additionally, if flash support is present, soundManager.preferFlash
means that MP3/MP4 will be handled by flash even if HTML5 support is present for those formats.
Additional HTML5 formats: OGG, WAV
WAVe (uncompressed audio) and OGG (a free/open-source alternative to MP3) 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. In 2011, Adobe suggested they would support OGG audio + video (combined, the "WebM" format) in a future release of flash. As of November 2013, this has yet to materialize.
You may need to make a few server configuration updates given the importance of MIME types and the use of certain HTTP headers when serving audio to HTML5 clients. See Client Requests for more.
HTML5 is not limited to OGG and WAV, of course, as the system is designed to be extensible. Support for other formats may exist, depending on what built-in support exists, and plug-ins or codecs the user has installed on their system.
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.)
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.)
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 Top-Level Properties
A few additional properties that hang off the soundManager
instance object
soundManager.altURL
soundManager.altURL
specifies an alternate path to soundManager.setupOptions.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.setupOptions.url
will be used for all cases.
soundManager.audioFormats
soundManager.audioFormats
defines a structure listing the audio codecs that will be tested for support under both HTML5 and Flash. Each type is defined by a file extension and MIME types, and optionally, a list of related extensions (eg. MPEG-4 content can be in an .mp4 file, but may also be .aac, or .m4a.)
Additionally, each format can be defined as "required", meaning that SM2 can fail to start if playback support is not found via either HTML5 or Flash. By default, MP3 is a required format.
soundManager.audioFormats = {
/**
* determines HTML5 support + flash requirements.
* if no support (via flash/HTML5) for "required" format, SM2 will fail to start.
* flash fallback is used for MP3 or MP4 if lacking HTML5 (or preferFlash = true)
* multiple MIME types may be tried looking for positive canPlayType() response.
*/
'mp3': {
'type': ['audio/mpeg; codecs="mp3"', 'audio/mpeg', 'audio/mp3', 'audio/MPA', 'audio/mpa-robust'],
'required': true
},
'mp4': {
'related': ['aac','m4a'], // additional formats under the MP4 container
'type': ['audio/mp4; codecs="mp4a.40.2"', 'audio/aac', 'audio/x-m4a', 'audio/MP4A-LATM', 'audio/mpeg4-generic'],
'required': false
},
'ogg': {
'type': ['audio/ogg; codecs=vorbis'],
'required': false
},
'wav': {
'type': ['audio/wav; codecs="1"', 'audio/wav', 'audio/wave', 'audio/x-wav'],
'required': false
}
};
soundManager Global Object
This is a collection of methods, 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 #1</a> * <a id="song2" href="song2.mp3">play song 2</a> */ 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 #1</a> var aLink = document.getElementById('song1'); if (soundManager.canPlayMIME(aLink.type)) { soundManager.createSound('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 clearOnPosition(id:string, msecOffset:integer, [callback:function])
- Clears the event listener set via
onPosition()
, in the same way it was registered. If the callback is omitted, any and all callbacks registered for the given offset will be cleared. - Example:
soundManager.clearOnPosition('mySound', 3000, positionHandler);
- Example 2:
soundManager.clearOnPosition('mySound', 3000);
- object:SMSound createSound(object:options)
- Creates a sound object, supporting an arbitrary number of optional arguments. Returns a
SMSound
object instance. At minimum, aurl
parameter is required. -
Minimal example:
var someSound = soundManager.createSound({ url: '/path/to/an.mp3' });
-
With optional parameters:
var mySoundObject = soundManager.createSound({ // optional id, for getSoundById() look-ups etc. If omitted, an id will be generated. id: 'mySound', url: '/audio/mysoundfile.mp3', // optional sound parameters here, see Sound Properties for full list volume: 50, autoPlay: true, whileloading: function() { console.log(this.id + ' is loading'); } });
Each
createSound()
call results in the creation of aSMSound
object which stores all properties, methods and events relevant to that particular sound instance. If you keep theSMSound
object in scope, you probably don't need to specify an ID. However, if you do provide anid
, you can easily get a reference to the given sound viasoundManager.getSoundById()
(for the above example, you would usemySound
.)When specifying an
id
you can also use controller-level convenience methods, i.e.,soundManager.play('mySound')
,soundManager.stop('mySound')
and so on.Individual sound objects can also easily be referenced as returned from
createSound()
:var mySoundObject = soundManager.createSound({ url: '/audio/mysoundfile.mp3' }); mySoundObject.play(); // SMSound object instance
For more SMSound parameters, 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');
- object:SMSound onPosition(id:string, 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:
soundManager.onPosition('mySound', 3000, function(eventPosition){console.log(this.id+' reached '+eventPosition});
- 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. - This method can also be used via
soundManager.setup({ onready: function() { ... } });
- 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. - Additionally, a
status
object containingsuccess
anderror->type
parameters is passed as an argument to your callback. - Example:
soundManager.ontimeout(function(status) { alert('SM2 failed to start. Flash missing, blocked or security error?'); alert('The status is ' + status.success + ', the error type is ' + status.error.type); });
- 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. - This method can also be used via
soundManager.setup({ ontimeout: function() { ... } });
- 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.ontimeout(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.
- reset()
- Effectively restores SoundManager's original state without rebooting (re-initializing).
- Similar to reboot() which destroys sound objects and the flash movie (as applicable), but also nukes any registered
onready()
and related callbacks. - Once
soundManager.reset()
has been called,soundManager.beginDelayedInit()
(orsoundManager.setup()
with aurl
property) may be called to re-init SM2.
- 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);
- setPlaybackRate(id:string,playbackRate:number)
- Sets HTML5 sound playback rate, between 0.5 and 4.0 of normal rate (1.0).
- Example:
soundManager.setPlaybackRate('mySound',1.5);
- See playbackRate (Mozilla) for more information.
- 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);
- setVolume(volume:integer) - overloaded method
- Sets the volume of all sound objects. Accepted values: 0-100. Affects volume property.
- Example:
soundManager.setVolume(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 pointing the sound object to
about:blank
, which replaces the current one from loading.
- 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();
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.
- object:SMSound clearOnPosition(msecOffset:integer, [callback:function])
- Clears the event listener set via
onPosition()
, in the same way it was registered. If the callback is omitted, any and all callbacks registered for the given offset will be cleared. - Example:
mySound.clearOnPosition(3000, positionHandler);
- Example 2:
mySound.clearOnPosition('mySound', 3000);
- 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.id+' reached '+eventPosition});
- If you need to fire an event relative to the true duration of the sound, reference its duration once the sound has fully-loaded - ie., at or after the
onload()
event - as the duration will not be completely accurate until that time.durationEstimate
may be referenced beforeonload()
, but it should not be relied on when "precise" timings of say, < 1 second are desired. - Example:
mySound.load({ onload: function() { this.onPosition(this.duration * 0.5, function(eventPosition) { console.log('the sound ' + this.id + ' is now at position ' + this.position + ' (event position: ' + eventPosition + ')'); }); } });
- Again, note that due to the interval / polling-based methods of both HTML5 and flash audio, sound status updates and thus precision can vary between 20 msec to perhaps 0.5 seconds and the sound's position property will reflect this delta when the
onPosition()
callback fires.
- 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);
- setPlaybackRate(playbackRate:number)
- Sets HTML5 sound playback rate, between 0.5 and 4.0 of normal rate (1.0).
- See playbackRate (Mozilla) for more information.
- 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 pointing the sound object to
about:blank
, which replaces the current one from loading.
- object:SMSound unmute()
- Unmutes the given sound. Affects muted property.
- Example:
mySound.unmute();
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.id+' 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.id
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 9 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()
- This method has been removed. Use the newer SMSound.onPosition() as a replacement.
- onbeforefinish()
- This method has been removed. Use the newer SMSound.onPosition() as a replacement.
- 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.id+' connected: '+(bConnect?'true':'false')); } }).play(); // will result in connection being made
- onerror(number:errorCode, string:description)
- Fires when a sound fails to load (HTML5/flash), or fails during load or playback (HTML5-only.)
- In the case of HTML5, an error code and matching description is provided when known.
-
This event is useful for explicit failure handling, particularly when tracking HTML5 errors. Note that HTML5 clients may fire errors after playback (or the first network request) has been initiated, so you should check the sound's
loaded
attribute before taking action.Under HTML5, the
loaded
attribute is assigned once the HTML5canplay
event has fired - meaning that the user agent has downloaded enough of the sound to start playback.In the case where
onerror
fires andloaded
is true, sound playback may be resumable if the user is shown a play button and initiates playback via tap/touch/click - particularly on mobile. In this case, callingstop()
within the error handler may help ensure that the sound's internal state is properly reset. - Example:
soundManager.createSound({ url: '/404.mp3', onerror: function(code, description) { console.log(this.id + ' failed?', code, description); // Did the sound fail to load entirely, or failed during playback / loading partially? if (this.loaded) { // HTML5 case: network error, or client aborted download etc.? this.stop(); // Reset sound state, to be safe // Show play / retry button to user in UI? } else { // Load failed entirely. 404, bad sound format, etc. } } }).play();
- HTML5 error codes and descriptions are as follows, from whatwg.org:
-
- Error code 1, MEDIA_ERR_ABORTED: Client aborted download at user's request.
- Error code 2, MEDIA_ERR_NETWORK: A network error of some description caused the user agent to stop fetching the media resource, after the resource was established to be usable.
- Error code 3, MEDIA_ERR_DECODE: An error of some description occurred while decoding the media resource, after the resource was established to be usable.
- Error code 4, MEDIA_ERR_SRC_NOT_SUPPORTED: Media (audio file) not supported ("not usable.")
- 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.id+' 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()
- This method has been removed. Use the newer SMSound.onPosition() as a replacement.
- 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');
- onsuspend()
- HTML5-only event: Fires when a browser has chosen to stop downloading of an audio file.
- Per spec: "The user agent is intentionally not currently fetching media data, but does not have the entire media resource downloaded."
- One use case may be catching the behaviour where mobile Safari (iOS) will not auto-load or auto-play audio without user interaction, and using this event to show a message where the user can click/tap to start audio.
- The HTML5
stalled
event may also fire in desktop cases and might behave differently across browsers and platforms, so careful testing is recommended.
- 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.id+' 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.
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()
.
- id
- Sound ID string as provided from the
id
parameter viacreateSound()
. Can be referenced asthis.id
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[id]
on the SoundManager global object. - Legacy note: The sound ID property used to be referenced as sID from within the sound object; this name is maintained for backward compatibility.
- 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. - Experimental feature: Multiple formats/encodings can now be applied to the
url
parameter by specifying an array instead of a single string. - Example:
soundManager.createSound({ id: 'foo', url: ['bar.ogg','bar.mp3'] });
- SoundManager 2 will use the first playable URL it finds (according to
canPlayURL()
and/orcanPlayType()
), and the URL property will then reflect the playable URL after that point. Note that this means the original array data will be lost. - In this alternate format, the array accepts "type" attributes.
-
soundManager.createSound({ id: 'foo', // useful for URLs without obvious filetype extensions url: [ {type:'audio/mp3',url:'/path/to/play.php?song=123'}, {type:'audio/mp4',url:'/path/to/play.php?song=256'} ] });
- 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.
- buffered
- Based loosely on the native HTML5 attribute, SM2 defines
buffered
as an array of objects which include start and end position (time) values. This property is updated during the SM2whileloading
event; internally, SM2 uses HTML5'sprogress
event to track changes. - It is important to note that the buffered values may not always be contiguous and can change, particularly if the user seeks within the file during downloading. With ranges, you can draw highlighted segments on a progress bar UI which would reflect the current "slices" of buffered data.
- Example: a
buffered
array of[{ start: 0, end: 2 }, { start: 5, end: 7 }];
shows a sound that has buffered data for the ranges 0-2 seconds, and 5-7 seconds. - In order to determine the total buffered data and thus "total percent loaded" under HTML5, you can loop through the
buffered
array and sum the total of(buffered[i].end - buffered[i].start)
. If you want to draw ranges, you can use the start and end values of each buffered item and draw that relative to the totalduration
(normalized asdurationEstimate
for flash compatibility). - Example:
var i, total = 0; for (i=0, j=this.buffered.length; i<j; i++) { // draw current range in progress bar UI? drawProgressUI(this.buffered[i].start, this.buffered[i].end); // sum of all ranges vs. whole file duration total += (this.buffered[i].end - this.buffered[i].start); }
- Note that under Flash, downloading is always sequential and thus the buffered array will always be a single item with
start: 0
and anend
value ofduration
(eg., the amount of currently-downloaded "time"). - Additional behaviour note: A browser might download additional bytes of a sound in advance under HTML5, but may only update the buffered state to reflect the newly-downloaded range(s) when the "playback head" reaches near the end of the current buffer. This can also be affected if the user seeks within the file.
- 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
- This property has been removed. Use the newer SMSound.onPosition() as a replacement.
- didJustBeforeFinish
- This property has been removed. Use the newer SMSound.onPosition() as a replacement.
- 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. - (Flash-only): Once the sound has fully loaded (
onload()
has fired),durationEstimate
will be updated with the final, Flash-calculated value ofduration
. - Note that the
durationEstimate
method works only with Constant Bitrate (CBR)-encoded MP3s due to the consistent data/time assumption. VBR-encoded MP3s will give inaccurate results. - HTML5 behaviour: Both
duration
anddurationEstimate
are updated at regular intervals during loading of HTML5 audio, directly referencing the duration property provided on the native HTML5 object. Unlike Flash, HTML5 typically gets the true and final duration value by the time playback begins.
- 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.
- isHTML5
- Boolean property indicating whether a sound object is using HTML5 Audio for playback. Treat as read-only.
- This should not really be relied on for anything, but it is provided as an indicator of support on a per-sound basis.
isHTML5
is set based on the URL provided tocreateSound()
, and is updated when the URL changes.
- 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.
- playbackRate
- Number affecting HTML5 sound playback rate, between 0.5 and 4.0 of normal rate (1.0).
- Can also be set via
setPlaybackRate()
. - See playbackRate (Mozilla) for more information.
- 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
- Under Flash,
readyState
will move from 0 to 1, and then change to 3 when the sound'sonload()
event fires (and all bytes have loade.) - Under HTML5,
readyState
will move from 0 to 1 when initializing the HTTP request (fromload()
), and will quickly change to 3 when the sound is ready to play. Note that HTML5 is buffer-based andonload()
means "enough audio data has buffered to begin playback".
- 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 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 Dynamic (Runtime) Properties
Some properties are dynamic, determined at initialisation or later during runtime, and should be treated as read-only.
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.html5Only [boolean, read-only]
This property is set during initialization and reflects whether SM2 is running in "100% HTML5 mode", based on support for required formats defined by soundManager.audioFormats
.
SoundManager Core Events
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.
- 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().
- ontimeout(callback:function(status),[scope])
- Queue
onload()
-style event listener(s), triggered when soundManager has successfully started. - Example:
soundManager.ontimeout(myOnTimeoutHandler); soundManager.ontimeout(myOtherHandler);
- For more detail and examples, see soundManager.ontimeout().
- onerror(status)
- Deprecation note: Use the newer soundManager.ontimeout() instead of this method.
- oninitmovie()
- Deprecation note: Use the newer soundManager.ontimeout() instead of this method.
- onload()
- Deprecation note: Use the newer soundManager.onready() instead of this method.
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.
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.id+' 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