Prerelease version 2.0b.20070118 - non-core features + documentation in development. Bugs/suggestions/feedback appreciated! :)

What is SoundManager?

(Choose your language)

SoundManager 2 is a Javascript Sound API which talks to Flash, effectively mapping most of Flash 8's native sound capabilities to Javascript. It enables web developers and front-end engineers to programmatically control sound in a cross-browser/platform way, using a language they already know.

In short, "It's Javascript Sound for the Web."

(Disclaimer: The following paragraphs are a parody, poking fun at the web 2.0 hype.)

SoundManagR 2.0 Betatm is a social, long-tail-oriented RIA-based enterprise javascript sound platform which leverages streaming AJAX push technology, Web 2.0, and leveraging. Including plenty of ajaxy goodness, this turn-key, SOA-based and Ajax-enhanced platform will take your Rich Enterprise Applications to the next level when mashed up with Web 2.0 collective wisdom of the crowd-wowing features such as drag and drop, auto-complete and real-time performance thanks to enterprise mashup servers.

By leveraging the collective blogosphere and rich folksonomy aspects of the web, it is expected that these supporting technologies may be joining the RIP (Rich Internet Professionals) and DOA (Development Of Asininity) groups within the next few years.*

Demos

Less Talk, More Show.

Some examples of Javascript-driven sound, and applications implementing SoundManager 2:

Getting Started

"I'd like to use this on my site. Where do I start?"

No problem! See this template example which shows the basic requirements of SoundManager 2. (For technical requirements, refer to Requirements + Specifications.)

Like a fine whiskey, SoundManager should come with a disclaimer that reads, "Use Responsibly." You should know when to stop, too.

Download

Current version: 2.0b.20070118

SoundManager v2.0b.20070118 (1.07 MB, .zip)

Includes API, ActionScript source, documentation, examples and demos.

Basic Use

SoundManager must first create and append the Flash movie used for handling sound via a small in-page script block.

soundManager.createMovie('/path/to/soundmanager2.swf');

This will kick off the initialization/load process, and a success (onload) or failure (onerror) handler will then be called.

Once soundManager.onload() has fired, sounds may be created, loaded and played in one call using minimal parameters.

soundManager.play('mySound','/path/to/some.mp3');

Sounds can also be created without automatically loading or playing, for later use:

soundManager.createSound('myNewSound','/path/to/some.mp3');

Once defined, sound objects have methods and properties which can be accessed by the soundManager controller.

soundManager.play('myNewSound');
soundManager.setVolume('myNewSound',50);
soundManager.setPan('myNewSound',-100);

Adding SoundManager 2 to your page

SM2 requires a single in-page Javascript call to append a hidden flash movie which provides the sound functionality. This call must be made within <body> (just before </body> is best) such that the movie will be created dynamically. In the non-IE browser case, the element is appended as a child of either <body> or the first <div> in the document.

Within <head>:

<script type="text/javascript" src="soundmanager2.js"></script>

Within <body>, or just before </body>:

<script type="text/javascript">soundManager.createMovie();</script>

Alternately, the path to the .swf may be specified, overriding the default:

<script type="text/javascript">soundManager.createMovie('/path/to/soundmanager2.swf');</script>

For a live example of this code, check the template example.

Initialization + Error Handling

In the event SoundManager encounters an error during loading, it will silently fail and disable itself; all subsequent calls to the soundManager controller object will return false. If defined, soundManager.onerror() will be called rather than soundManager.onload().

During development, SoundManager may throw custom errors to help debugging. For post-live testing, debug mode can be forced by appending debug=1 somewhere in the URL (eg. #debug=1 or ?debug=1) and refreshing the page. You may also view some live debug output on this page.

SoundManager onload equivalent

This is a user-defined onload-style function implemented by SoundManager. Because of the overhead associated in creating and initialising the Flash and Javascript code necessary for SoundManager to function, a separate "onload"-type function is provided so your code can hook into it.

soundManager.onload = function() {
  // soundManager should be ready to use/call at this point
  soundManager.createSound('mySound','/path/to/mysoundfile.mp3');
  soundManager.play('mySound');
}

SoundManager onerror equivalent

Note also that if SoundManager fails to load, it will call soundManager.onerror() if defined. You can assign a handler here to be notified of failure, and take appropriate action.

soundManager.onerror = function() {
  // soundManager failed to initialize (security restrictions, no support, missing SWF etc.)
  // Notify user if needed, disable sound-specific functionality etc.
}

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

SoundManager API

The following are methods, collections, properties and event handlers provided by the globally-scoped soundManager Javascript object. Both sound properties and methods can be set on a global (inherited) default, or per-sound basis.

SoundManager Core Methods

createSound(object:options)
Creates a sound with an arbitrary number of optional arguments.
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,
 onprogress: soundIsLoading // remember to omit comma on the last item
});

(Note: Code formatting is stylistic, not necessarily recommended.) See Object Literal Format.

createSound(id:string,url:string)
Creates a sound with the specified ID and URL (simple method.)
Example: soundManager.createSound('mySound','/audio/mysoundfile.mp3');
play(id:string,[options object])
Starts playing the sound specified by ID. (Will start loading if applicable, and will play ASAP.)
Returns a boolean value indicating "sound created", ie. if the related sound object didn't exist prior to this call and was created to do so.
Example: soundManager.play('mySound');
Note that the second parameter, options object, is not required and can take almost any argument from the object literal format (eg. volume.) These should be applied on an instance-specific basis (only overriding existing options for this play instance), but may persist due to an incomplete implementation. (To be fixed.)
Example 2: soundManager.play('mySound',{volume:50,onfinish:playNextSound});
setPosition(id:string,msecOffset:integer)
Seeeks to a given position within a sound, specified by miliseconds (1000 msec = 1 second)
Example: soundManager.setPosition('mySound',2500);
pause(id:string)
Pauses the sound specified by ID. (Does not toggle.)
Example: soundManager.pause('mySound');
resume(id:string)
Resumes the currently-paused sound specified by ID.
Example: soundManager.resume('mySound');
togglePause(id:string)
Pauses/resumes play on the sound specified by ID.
Example: soundManager.pause('mySound');
setVolume(id:string,volume:integer)
Sets the volume of the sound specified by ID. Accepted values: 0-100
Example: soundManager.setVolume('mySound',50);
stop(id:string)
Stops playing the sound specified by ID.
Example: soundManager.stop('mySound');
stopAll()
Stops any currently-playing sounds.
Example: soundManager.stopAll();
unload(id:string)
Stops loading the sound specified by ID, canceling any current HTTP request.
Example: soundManager.unload('mySound');
Note that SoundManager does this by loading a new, tiny "stub" MP3 file, ./data/null.mp3, which replaces the current one from loading. (TODO: Put URL in config section)
getSoundById(id:string)
Returns an SMSound object specified by ID.
Example: var mySMSound = soundManager.getSoundById('mySound');
loadFromXML(xmlURL:string)
Loads and creates sounds as defined in a SoundManager v1 XML file (legacy)
Example: soundManager.loadFromXML('/path/to/some.xml');
XML format example: MPC drumkit XML file

Sound Properties Object

The soundManager.defaultOptions object contains parameters which are inherited by default when sounds are 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, as the defaults will be inherited if unspecified.

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

soundManager.defaultOptions = {
  'debugMode': true,             // enable debug/status messaging, handy for development/troubleshooting
  'autoLoad': false,             // enable automatic loading (otherwise .load() will be called on demand with .play()..
  'stream': true,                // allows playing before entire file has loaded (recommended)
  'autoPlay': false,             // enable playing of file as soon as possible (much faster if "stream" is true)
  'onid3': null,                 // callback function for "ID3 data is added/available"
  'onload': null,                // callback function for "load finished"
  'whileloading': null,          // callback function for "download progress update" (X of Y bytes received)
  'onplay': null,                // callback for "play" start
  'whileplaying': null,          // callback during play (position update)
  'onstop': null,                // callback for "user stop"
  'onfinish': null,              // callback function for "sound finished playing"
  'onbeforefinish': null,        // callback for "before sound finished playing (at [time])"
  'onbeforefinishtime': 5000,    // offset (milliseconds) before end of sound to trigger beforefinish..
  'onbeforefinishcomplete':null, // function to call when said sound finishes playing
  'onjustbeforefinish':null,     // callback for [n] msec before end of current sound
  'onjustbeforefinishtime':200,  // [n] - if not using, set to 0 (or null handler) and event will not fire.
  'multiShot': true,             // let sounds "restart" or layer on top of each other when played multiple times..
  'pan': 0,                      // "pan" settings, left-to-right, -100 to 100
  'volume': 100                  // self-explanatory. 0-100, the latter being the max.
}

To modify global SoundManager defaults, edit the main soundmanager2.js file (look for above section in code) or assign new values in your own application script before window.onload() fires.

Example per-application override:

soundManager.defaultOptions.debugMode = false; // disable debug mode
soundManager.defaultOptions.volume = 33;       // set global default volume

SoundManager Core Events

onload()
Function called when SoundManager has successfully loaded.
Example: soundManager.onload = function() { alert('SoundManager ready to use'); }
Once this function has been called, all core methods will be available to use.
Note that onload() is not called when SoundManager fails to load; instead, onerror() is called.
onerror()
Function called when SoundManager fails to load.
Example: soundManager.onerror = function() { alert('SoundManager failed to load'); }

Object Collections

soundIDs[]
An array of sound ID strings, ordered by creation.
sounds[]
A "hash"/object literal of SMSound objects indexed by sound ID (as in sounds['mySound']), used internally by SoundManager.

Requirements + Specifications

Prerequisites (client)

Supported Browsers/Platforms

Javascript-to-flash communication is possible through Flash 8's ExternalInterface feature, which (as I understand) uses a standard browser plugin architecture implemented by each browser manufacturer (see NPAPI.) As a result, the following browsers should be supported:

For reference, see Adobe's ExternalInterface support page which documents supported browsers.

At this time, not all combinations of browser/OS have been tested. Some unlisted configurations may be supported, but have not been tested.

Unsupported/Buggy

The following browser/OS combinations have been reported as buggy or non-supported:

Revision History

"Use Responsibly"

A Word Of Vice

Not every button, link, element or paragraph on the web needs to zoom, move, change colour and be noisy, repetitive and annoying all at the same time. Use your own discretion! :)

Demo Credits

Background Tile

Modified from squidfingers.com (free patterns)

Sounds - MPC Demo

Sounds downloaded from AKAI.com

General

SoundManager was written to meet a desire to have Javascript-driven sound for interactive web-based projects. It is free for use in both personal and commercial projects (specific licensing info pending.) It was originally developed for personal use and has been packaged with the hopes of being useful to others.

Links

About

Scott Schiller (contact) is a Front-end Engineer (previously "Web Developer") who builds fun creative and technical stuff on the web - or failing that, tries - when he has free time. He likes building cool things which contribute to, yet enjoys mocking, the Web 2.0 meme. (See How Web 2.0-Aware Are You?)

Debug Output

Live debug info from SoundManager 2, active on this page for demo tests.

If you're seeing errors here or in demos, this info can help in troubleshooting.