SoundJS Documentation

repository·master·Indexed 26 days ago

https://github.com/createjs/soundjs

A JavaScript library providing a consistent API for web audio development across different browsers and environments. SoundJS uses a plugin-based architecture supporting Web Audio, HTML5 Audio, Cordova, and Flash. It features core classes like createjs.Sound for playback and createjs.SoundInstance for controlling audio properties such as volume, pan, and position, and integrates with PreloadJS for audio file loading.

Tokens
7.4K
Snippets
18
Records
59
Agent score
88%

What's inside SoundJS

  1. Overview of SoundJS core classes

    master

    SoundJS provides a consistent API for web audio through several key classes:

    • createjs.Sound: The core API for playing sounds. Use createjs.Sound.play(sound, ...options) to create a sound instance.
    • createjs.SoundInstance: A controllable object returned by playing a sound. It wraps the underlying plugin and allows you to pause, mute, stop, or change volume, pan, and position.
    • Plugins: SoundJS uses a plugin model to support different environments:
      • WebAudioPlugin: The default plugin using Web Audio APIs. Note: WebAudio may fail when running files locally, triggering the fallback.
      • HTMLAudioPlugin: The built-in fallback that uses the HTML5 <audio> tag.
      • CordovaAudioPlugin: For Cordova, PhoneGap, or Ionic apps. Requires manual registration.
      • FlashAudioPlugin: Uses a Flash shim and SWFObject. Requires manual setup and registration.
  2. Include SoundJS audio plugins

    master

    To support specific playback environments, include the corresponding plugin. Plugins are provided in both uncompressed and minified versions:

    • flashplugin.js: Utilizes Adobe Flash for audio playback.
    • cordovaplugin.js: Utilizes Cordova/PhoneGap APIs for audio playback.
  3. Shortcut the createjs namespace

    master

    If you want to avoid typing the full createjs prefix, you can create a shortcut by assigning the createjs object to a shorter variable after the library has been loaded.

    <script src="easeljs.js"></script>
    <script>
    var c = createjs; // creates a reference to the createjs namespace in "c"
    var foo = new c.Shape();
    </script>
  4. Select the appropriate SoundJS library version

    master

    The lib directory provides different versions of SoundJS depending on your needs for stability or debugging:

    • soundjs.js: The most recent tagged (stable) version of all SoundJS classes. Use this for development and debugging.
    • soundjs.min.js: The most recent tagged version, minified for production deployment.
    • soundjs-NEXT.js: Contains the latest SoundJS classes (in-progress development). Use this to test upcoming features.
    • soundjs-NEXT.min.js: A minified version of the latest updates to the library.
  5. Remove the createjs namespace

    master

    To remove the namespace entirely and make the library compatible with legacy content (such as Flash Pro Toolkit output for CreateJS v1.0), assign window to the createjs variable before loading the library scripts. This causes the classes to be defined directly on the global window object.

    <script>
    var createjs = window; // sets window as the createjs namespace
    </script>
    <script src="easeljs.js"></script>
  6. Access SoundJS via the createjs namespace

    master

    In this version of SoundJS, all class definitions are contained within the createjs namespace by default. To call methods like play, you must access them through this namespace.

    Instead of calling SoundJS.play(id) directly, use createjs.SoundJS.play(id).

    var bar = createjs.SoundJS.play(id);
  7. Configure audio sprite playback

    master

    Audio sprites allow you to group multiple audio assets into a single file to reduce network requests and bypass browser limits on the number of concurrent audio tags.

    To use audio sprites, include a data.audioSprite array in your sound registration object. Each sprite entry requires an id, startTime (in milliseconds), and duration (in milliseconds).

    You can also play specific segments of a sound on the fly by providing startTime and duration options to the play method.

    var assetsPath = "./assets/";
    var sounds = [{
        src:"MyAudioSprite.ogg", 
        data: {
            audioSprite: [
                {id:"sound1", startTime:0, duration:500},
                {id:"sound2", startTime:1000, duration:400},
                {id:"sound3", startTime:1700, duration: 1000}
            ]
        }
    }];
    
    createjs.Sound.registerSounds(sounds, assetsPath);
    // Play a specific sprite by ID
    createjs.Sound.play("sound2");
    
    // Or play a segment on the fly
    createjs.Sound.play("MyAudioSprite", {startTime: 1000, duration: 400});
  8. HTMLAudioPlugin limitations and best practices

    master

    When using the HTMLAudioPlugin, be aware of the following constraints:

    General Limitations

    • Instance Limit: There is a limit to how many audio tag instances can be used. Use createjs.Sound.MAX_INSTANCES (defaulting to 30) as a guide. Audio sprites are recommended to mitigate this.
    • IE Limitations: Volume changes may be delayed once playback starts. MP3 encoding works best with 64kbps. Very short samples may be cut off.
    • Safari: Requires Quicktime to be installed.

    Platform Specifics

    • iOS 6: Highly restricted. Can only have one <audio> tag, cannot preload/autoplay, and cannot cache. It is strongly recommended to use WebAudioPlugin for iOS (6+).
    • Android Native: Volume cannot be controlled via code; only the user can set device volume. Audio must be played inside a user-initiated event (touch/click), which prevents looping or using delays.
    • Android Chrome (26.0.1410.58): Can only play one sound at a time and sounds are not cached.
  9. Unlock Web Audio on iOS with playEmptySound()

    master

    On iOS devices, audio is initially muted and requires a user-initiated event (like a touchstart or mousedown) to unlock. You can manually trigger an unlock by playing an empty sound within a user interaction handler.

    function handleTouch(event) {
        createjs.WebAudioPlugin.playEmptySound();
    }
  10. Basic usage of SoundJS

    master

    To use SoundJS, you can register sounds using createjs.Sound.registerSound() and play them using createjs.Sound.play(). You can also define alternateExtensions to allow the library to look for fallback audio formats (e.g., if an .ogg file is requested but not supported, it can look for an .mp3).

    Listen for the fileload event on createjs.Sound to know when your assets are ready for playback.

    createjs.Sound.on("fileload", handleLoadComplete);
    createjs.Sound.alternateExtensions = ["mp3"];
    createjs.Sound.registerSound({src:"path/to/sound.ogg", id:"sound"});
    
    function handleLoadComplete(event) {
    	createjs.Sound.play("sound");
    }
  11. Configure WebAudioPlugin context and scratch buffer

    master
    Advanced users can provide a custom AudioContext or a _scratchBuffer to the WebAudioPlugin before calling Sound.registerPlugins() or Sound.initializeDefaultPlugins(). This is useful for managing shared audio resources or handling specific browser requirements.