# SoundManager 2: Documentation

## API Elements

SoundManager and SMSound API

- ### SoundManager

  #### Properties

  - allowScriptAccess
  - altURL
  - audioFormats
  - consoleOnly
  - debugFlash
  - debugMode
  - defaultOptions
  - flash9Options
  - features
  - flashLoadTimeout
  - flashPollingInterval
  - flashVersion
  - html5Only
  - html5PollingInterval
  - movieStarOptions
  - preferFlash
  - url
  - useConsole
  - useFastPolling
  - useFlashBlock
  - useHighPerformance
  - useHTML5Audio
  - wmode
  - waitForWindowLoad
  - allowPolling
  - nullURL
  - useMovieStar

  #### Methods

  - canPlayLink()
  - canPlayMIME()
  - canPlayURL()
  - createSound()
  - destroySound()
  - getMemoryUse()
  - getSoundById()
  - load()
  - mute()
  - ok()
  - onPosition()
  - pause()
  - pauseAll()
  - play()
  - reboot()
  - resume()
  - resumeAll()
  - setPan()
  - setPosition()
  - setVolume()
  - supported()
  - stop()
  - stopAll()
  - toggleMute()
  - togglePause()
  - unload()
  - unmute()

  #### Events

  - onerror
  - oninitmovie
  - onload
  - onready()
  - ontimeout()

- ### SMSound (Sound Object)

  #### Parameters (Instance Options)

  - autoLoad
  - autoPlay
  - bufferTime
  - eqData
  - from
  - isMovieStar
  - loops
  - multiShot
  - multiShotEvents
  - pan
  - peakData
  - position
  - serverURL
  - sID
  - stream
  - to
  - type
  - url
  - usePolicyFile
  - volume
  - waveformData
  - onbeforefinishtime
  - onjustbeforefinishtime

  #### Dynamic Properties

  - bytesLoaded
  - bytesTotal
  - isBuffering
  - connected
  - duration
  - durationEstimate
  - isHTML5
  - loaded
  - muted
  - paused
  - playState
  - position
  - readyState
  - didBeforeFinish
  - didJustBeforeFinish

  #### Events

  - onbufferchange
  - onconnect
  - ondataerror
  - onfinish
  - onload
  - onpause
  - onplay
  - onresume
  - onsuspend
  - onstop
  - onid3
  - whileloading
  - whileplaying
  - onbeforefinishcomplete
  - onbeforefinish
  - onjustbeforefinish

  #### Methods

  - destruct()
  - load()
  - onPosition()
  - mute()
  - pause()
  - play()
  - resume()
  - setPan()
  - setPosition()
  - setVolume()
  - stop()
  - toggleMute()
  - togglePause()
  - unload()
  - unmute()

## SoundManager Configuration

Flash URLs, version + performance options

Just getting started? See the basics. For nicely-formatted and commented source code, see the generated documentation.

### SoundManager Properties

The soundManager object has many configurable properties which set debug mode, determine the flash movie path and other behaviours. Below are the default settings for SoundManager 2, which are appropriate for the majority of use cases - you shouldn't need to change them.

Note: The only property requiring customization is `soundManager.url`, which must be assigned a 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.)

- soundManager.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 if not specified, depending on flashVersion and debugMode settings.
- soundManager.allowScriptAccess = 'always';
  // for scripting the SWF (object/embed property), 'always' or 'sameDomain'
- soundManager.audioFormats = { ... };
  // defines audio types to be tested for HTML5 vs. Flash support, and which formats are "required" (by default, MP3 is required for SM2 to work.)
- soundManager.bgColor = '#ffffff';
  // SWF background color. N/A when wmode = 'transparent'
- soundManager.consoleOnly = true;
  // if console is being used, do not create/write to #soundmanager-debug
- soundManager.debugMode = true;
  // enable debugging output (console.log() with HTML fallback)
- soundManager.debugFlash = false;
  // enable debugging output inside SWF, troubleshoot Flash/browser issues
- soundManager.flashVersion = 8;
  // flash build to use (8 or 9.) Some API features require 9.
- soundManager.flashPollingInterval = null;
  // msec affecting whileplaying/loading callback frequency. If null, default of 50 msec is used.
- soundManager.html5PollingInterval = null;
  // msec affecting whileplaying/loading callback frequency. If null, native HTML5 update events are used.
- soundManager.html5Test = /^(probably|maybe)$/i;
  // HTML5 Audio() format support test. Use /^probably$/i; if you want to be more conservative.
- soundManager.flashLoadTimeout = 1000;
  // msec to wait for flash movie to load before failing (0 = infinity)
- soundManager.noSWFCache = false;
  // if true, appends ?ts={date} to break aggressive SWF caching.
- soundManager.preferFlash = true;
  // overrides useHTML5audio. if true and flash support present, will try to use flash for MP3/MP4 as needed since HTML5 audio support is still quirky in browsers.
- soundManager.useConsole = true;
  // use console.log() if available (otherwise, writes to #soundmanager-debug element)
- soundManager.useFlashBlock = false;
  // requires flashblock.css, see demos - allow recovery from flash blockers. Wait indefinitely and apply timeout CSS to SWF, if applicable.
- soundManager.useHighPerformance = false;
  // position:fixed flash movie can help increase js/flash speed, minimize lag
- soundManager.useHTML5Audio = true;
  // use HTML5 Audio() where API is supported (most Safari, Chrome versions), Firefox (no MP3/MP4.) Ideally, transparent vs. Flash API where possible.
- soundManager.waitForWindowLoad = false;
  // force SM2 to wait for window.onload() before trying to call soundManager.onload()
- soundManager.wmode = null;
  // flash rendering mode - null, 'transparent', or 'opaque' (last two allow z-index to work)
- soundManager.allowPolling = true;
  // enable flash status updates. Required for whileloading/whileplaying.
- soundManager.nullURL = 'about:blank';
  // (Flash 8 only): URL of silent/blank MP3 for unloading/stop request.

To modify global SoundManager default parameters for SM2 itself or for all sound objects, edit the main soundmanager2.js file (look for the above block near the top) 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.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.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 and/or HTML5) for a "required" format, SM2 will fail to start.
       * flash fallback is used for MP3 or MP4 if HTML5 can't play it (or if preferFlash = true)
       * multiple MIME types may be tested while trying to get a 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.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.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.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.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.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 fire `onfinish()` multiple times. (Previous behaviour did not layer sounds, but would re-play a single instance.)
- `waveformData` array: 256 waveform data values available while playing sound
- `eqData` array: 256 EQ spectrum data values available while playing sound
- `peakData` 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.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.

#### soundManager.html5Only [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.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.

#### soundManager.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 is still quirky and has bugs, `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. If you prefer 100% HTML5 mode even when Flash is present, set this property to `false`.

#### soundManager.url

`soundManager.url` specifies the "online", generally HTTP-based path which SM2 will load .SWF movies from. The "local" (current) directory will be used by default. The appropriate .SWF required (depending on the desired Flash version) will be appended to the URL.

Example: `soundManager.url = '/path/to/swf-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`.

#### soundManager.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.

#### 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/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.

#### 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.useHTML5Audio

Beta notice: HTML5 support is in active development. Experimental API bits will be labeled as such, but should remain largely forward-compatible. See Revision History for the latest updates on HTML5 playback support.

`soundManager.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+, 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.

In the case when HTML5 + Flash are present, Flash will presently get preference for MP3/MP4 because of `soundManager.preferFlash = true` as HTML5 audio is still buggy between browsers and platforms; where desired, you can set `preferFlash = false` and in some cases enjoy 100% HTML5 mode (eg., under Safari, IE 9 and Chrome.) For some browsers, Flash will be needed if support for formats like MP3 (not supported via HTML5 in Firefox) are "required."

##### 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` 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 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 `soundManager.html5Test` to be `/probably/i` if you want to be more strict, for example.

Only Safari, IE 9 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. Additionally, if flash support is present, `soundManager.preferFlash` means that MP3/MP4 get flash by default as HTML5 is still a bit unstable and subject to bugs across many devices and OSes.

##### 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. Adobe have indicated they will support OGG audio and video (combined, the "WebM" format) in a future release of flash. As of July 2011, no official date has been set.

If you plan on serving OGG media to HTML5, 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 these files. See Mozilla's Configuring Servers For Ogg Media 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.)

#### 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()` and `canPlayURL()` as needed to estimate the playability of an HTML link; this means both the `href` and `type` 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` or `audio/mpeg`
  - MovieStar-only formats: `/^audio\/(?:x-)?(?:mp(?:eg|3)|mp4a-latm|aac|speex)\s*;?/i;` - eg. `audio/m4a or audio/aac`
  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 return `null` instead of `false`.

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 return `null` instead of `false`.

object:SMSound createSound(object:options)
  Creates a sound with an arbitrary number of optional arguments. Returns a `SMSound` object instance. Requires `id` and `url` 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: soundIsLoadingFunction
      });

  Each `createSound()` call results in the creation of a `SMSound` 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 other `createSound` options passed (eg., `url` or `volume`, 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's `position` is tracked in Flash; therefore, subsequent "shots" will not have onPosition() events being fired.
  Example: `soundManager.onPosition('mySound', 3000, function(eventPosition){console.log(this.sID+' 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. The `onready()` queue is processed before `soundManager.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.
  Additionally, a `status` object containing `success` and `error->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 the `useFlashBlock` 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.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.

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 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();`

## 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's `position` 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});`
  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 before `onload()`, 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 - 5000, function() {
            console.log('the sound ' + this.sID + ' is now at position ' + this.position);
          });
        }
      });

  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);`

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();`

## 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()
  This method has been removed. Use the newer SMSound.onPosition() as a replacement.
  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()
  This method has been removed. Use the newer SMSound.onPosition() as a replacement.
  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. Affects `connected` 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()
  This method has been removed. Use the newer SMSound.onPosition() as a replacement.
  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');`

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.sID+' loading, '+this.bytesLoaded+' of '+this.bytesTotal);`
  Note that the `duration` property starts from 0 and is updated during `whileloading()` 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 using `bytesLoaded`, `bytesTotal` and `duration` while loading. Once fully-loaded, `duration` will reflect the true and accurate value.

whileplaying()
  Fires at a regular interval when a sound is playing, and a position (time) change is detected. The relevant, updated property is `position`.
  Example handler code: `soundManager._writeDebug('sound '+this.sID+' playing, '+this.position+' of '+this.duration);`

## 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 via `createSound()` or `play()`. Can be referenced as `this.sID` from within sound object event handlers such as `onload()`, `whileloading()` or `whileplaying()`, etc.
  If an ID is known, the related SMSound object can be retrieved via `getSoundById` or directly referencing `sounds[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 as `onload()` or `whileplaying()`, 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/or `canPlayType()`), 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 to `true` if your sound options have an `onid3()` 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
  This property has been removed. Use the newer SMSound.onPosition() as a replacement.
  Boolean indicating whether `beforeFinish()` condition was reached.

didJustBeforeFinish
  This property has been removed. Use the newer SMSound.onPosition() as a replacement.
  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 calculating `parseInt((self.bytesTotal/self.bytesLoaded)*self.duration)` and is updated with each `whileloading()` 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 during `whileplaying()`. 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 to `createSound()`, 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 to `load` or `play` will result in a connection attempt being made, and `onconnect()` 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()` and `toggleMute()` methods to affect state.

paused
  Boolean indicating pause status. True/False.
  Treat as read-only; use `pause()`, `resume()` and `togglePause()` methods to affect state.

peakData = {left:0.0, right:0.0}
  Object literal format including `left` and `right` properties with floating-point values ranging from 0 to 1, indicating "peak" (volume) level. Updated during `whileplaying()`. 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 like `canPlayURL()`.
  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 during `whileplaying()`. 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.

destruct() (also called via soundManager.destroySound())
load()
mute()
pause()
play([options object])
resume()
setPosition(msecOffset:integer)
togglePause()
setVolume(volume:integer)
setPan(pan:integer)
stop()
unload()
unmute()

## SoundManager Default Options

An optional object specifying event handlers etc., passed to `createSound()` and `play()`.

### SoundManager Global Sound Object Defaults

The `soundManager.defaultOptions` object contains default parameters inherited by sound objects made via `createSound()`. They can be overridden on a per-sound basis at create time, or changed dynamically in some cases. Note that none of these options are required when calling `createSound()` except for `id` and `url`; the others will inherit the default values if unspecified.

`soundManager.defaultOptions` apply the properties and event handlers as specified above. Defaults are shown below as an example.

    soundManager.defaultOptions = {
      autoLoad: false,       // enable automatic loading (otherwise .load() will call with .play())
      autoPlay: false,       // enable playing of file ASAP (much faster if "stream" is true)
      from: null,            // position to start playback within a sound (msec), see demo
      loops: 1,              // number of times to play the sound. Related: looping (API demo)
      multiShot: true,       // let sounds "restart" or "chorus" when played multiple times..
      multiShotEvents: false,// allow events (onfinish()) to fire for each shot, if supported.
      onid3: null,           // callback function for "ID3 data is added/available"
      onload: null,          // callback function for "load finished"
      onstop: null,          // callback for "user stop"
      onfinish: null,        // callback function for "sound finished playing"
      onpause: null,         // callback for "pause"
      onplay: null,          // callback for "play" start
      onresume: null,        // callback for "resume" (pause toggle)
      position: null,        // offset (milliseconds) to seek to within downloaded sound.
      pan: 0,                // "pan" settings, left-to-right, -100 to 100
      stream: true,          // allows playing before entire file has loaded (recommended)
      to: null,              // position to end playback within a sound (msec), see demo
      type: null,            // MIME-like hint for file pattern / canPlay() tests, eg. audio/mp3
      usePolicyFile: false,  // enable crossdomain.xml request for remote domains (for ID3/waveform access)
      volume: 100,           // self-explanatory. 0-100, the latter being the max.
      whileloading: null,    // callback function for updating progress (X of Y bytes received)
      whileplaying: null,    // callback during play (position update)
      onbeforefinish: null,  // callback for "before sound finished playing (at [time])"
      onbeforefinishtime: 5000,    // offset (milliseconds) from sound end, call beforefinish..
      onbeforefinishcomplete: null,// function to call when said sound finishes playing
      onjustbeforefinish: null,    // callback for [n] msec before end of current sound
      onjustbeforefinishtime: 200, // if unused, set to 0 (or null handler), event will not fire.

      // *** merged soundManager.flash9Options, as applicable ***
      isMovieStar: null,    // "MovieStar" MPEG4 audio mode. Null (default) = auto detect MP4, AAC etc. based on URL. true = force on, ignore URL
      usePeakData: false,   // enable left/right channel peak (level) data
      useWaveformData:false,// enable sound spectrum (raw waveform data) - Note: May be CPU-intensive, UI redraw/layout etc.
      useEQData: false,     // enable sound EQ (frequency spectrum data) - Note: CPU potential also.
      onbufferchange: null, // callback for "isBuffering" property change
      ondataerror: null     // callback for waveform/eq data access error (flash playing audio in other tabs/domains)

      // *** merged soundManager.movieStarOptions, as applicable ***
      bufferTime: null,     // seconds of data to buffer (null = flash default of 0.1 - if AAC gappy, try up to 3 seconds)
      serverURL: null,      // rtmp: flash media server to connect to, required for RTMP
      onconnect: null       // rtmp: callback for connection to flash media server

    }

As a simple example, the following code would override the default `autoPlay`, `pan` and `volume` options for a given sound:

    soundManager.createSound({
      id: 'mySound',
      url: '/path/to/some.mp3',
      autoPlay: true,
      pan: -75,
      volume: 50
    });

Note: For live examples, see the code behind the "page as playlist" demo which uses much of this functionality.

### Sound Properties Object: Version-specific Options (Merging)

Some sound properties object items (eg. `usePeakData`) are flash version-specific, non-default and are intentionally separated from `soundManager.defaultOptions`. Flash 9-specific options fall under this category.

`soundManager.flash9Options` and `soundManager.movieStarOptions` are both defined as separate objects, and if supported according to `flashVersion` and `defaultOptions` parameters, are merged "without nesting" into `soundManager.defaultOptions`.

    soundManager.flash9Options = {
      isMovieStar: null,      // "MovieStar" MPEG4 audio mode. Null (default) = auto detect MP4, AAC etc. based on URL. true = force on, ignore URL
      usePeakData: false,     // enable left/right channel peak (level) data
      useWaveformData: false, // enable sound spectrum (raw waveform data) - WARNING: May set CPUs on fire.
      useEQData: false,       // enable sound EQ (frequency spectrum data) - WARNING: Also CPU-intensive.
      onbufferchange: null,	  // callback for "isBuffering" property change
      ondataerror: null	  // callback for waveform/eq data access error (flash playing audio in other tabs/domains)
    }
    soundManager.movieStarOptions = {
      bufferTime: null  // seconds of data to buffer (null = flash default of 0.1 - if AAC gappy, try up to 3 seconds)
    }
    // if applicable, these options are merged into soundManager.defaultOptions at SM2 init.
    // soundManager.flash9Options.isMovieStar -> soundManager.defaultOptions.isMovieStar, etc.

#### defaultOptions.peakData vs. flash9Options.usePeakData

Note that `soundManager.defaultOptions.peakData` will be undefined until SoundManager 2 has self-initialized, at which point it determines the flash version to use and creates the .SWF, etc. Only then will defaultOptions be populated with optional option parameters, if applicable.

Once SM2 has written out the .SWF, it is safe to modify `soundManager.defaultOptions.usePeakData` directly, for example - but if making changes before initialization, eg., at the time when you are setting `soundManager.flashVersion`, it is best to modify the source objects as they haven't yet been merged. ie., `soundManager.flash9Options.usePeakData = true;`

## 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(status)
  Deprecation note: Use the newer soundManager.ontimeout() instead of this method.
  Function called when SoundManager fails to successfully initialise after Flash attempts an init call via ExternalInterface.
  Example: `soundManager.onerror = function(status) { alert('SoundManager failed to load: ' + status.type); }`
  This handler should be called if there is an ExternalInterface problem or other exceptions that fire when the initialisation function is called.
  If a specific type of error occurred, it will be provided in the status object as a `type` parameter.
  If you want multiple listeners for this event, see soundManager.ontimeout().
oninitmovie()
  Deprecation note: Use the newer soundManager.ontimeout() instead of this method.
  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.
  Deprecation note: Use the newer soundManager.onready() instead of this method.
  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 in `sounds['mySound']` or `sounds.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