SoundJS: Basics and Best Practices

Synopsis: Play audio with best practices.
Topics: sound, play, best practices, basics
Target: SoundJS 0.5.2+

This tutorial is part of the SoundJS GitHub repository.
Check out the repository for more tutorials and a handful of helpful samples.

Intro

SoundJS is a JavaScript library that provides a simple API for playing sounds in a consistent cross-browser supported way. Sounds great doesn't it? But how do you actually make it work? And what are some good approaches to take? We explore these questions in this tutorial.

After reading this article, you should be able to play audio on a website on any desktop browser that supports audio in some form, using a single, easily maintained code base. The end result will be very similar to the "JustPlay" example in the SoundJS GitHub repository.

Basics

This tutorial assumes that you already have a basic grasp of html and javascript. We'll start with some best practices.

In all of our SoundJS examples you'll see that CSS is always loaded in the <HEAD>. This is so the page styles are loaded before the body content that is displayed to the user, so they never see un-styled content.

Conversely, all of our scripts are loaded at the bottom of the <BODY>. This is because JavaScript has a blocking behavior, preventing the display of any content following it until the script load has completed. Generally it is better to show a user something, then add functionality using JavaScript, rather then to make the user wait for everything to load first.

Initial Setup

After creating a new html document, the first thing we'll need to play audio is, not surprisingly, a link to the SoundJS library. SoundJS is hosted on a CDN, so in the HTML body we create a <SCRIPT> tag and set it's source to http://code.createjs.com/soundjs-0.5.2.min.js. Note that the SoundJS library is available globally under the "createjs" namespace. For example the primary class "Sound" is accessed in code with createjs.Sound.

Next, create an inline script that does the actual work of playing the sound. In general, it is a better practice to create an external JavaScript file and load it in the html. This gives the benefit of separating code into more maintainable chunks and allows browsers to cache the files for quicker loads if users revisit your site or visit different areas in your site that use the same script. However, for our purposes, it is easier to demonstrate how to play sound inline in the HTML file.

Inside this script, create an init function, which will be called by adding an onload handler to the <BODY> tag. The onload callback will execute the init function when everything on the page has loaded. The body tag should look similar to the following:

Plugins

Once setup is complete, we can get directly to loading and playing sounds. It is important to know, however, that SoundJS uses a number of plugins to enable audio playback in different browsers. There are no additional steps to initialize the plugins, and the default plugin set (Web Audio and HTML Elements) will work in the majority of modern browsers. For this tutorial, the default plugin set will be fine.

Plugin selection will happen automatically the first time audio is preloaded or played, however if you need to determine if audio will play before that (to show a message for example), a handy method exists to manually initialize the default plugins: initializeDefaultPlugins() can be called at any time.

Internal Preloading

It is a best practice to preload audio so it is ready for immediate playback. We have an excellent tutorial on preloading techniques, but for this example we'll only be using a basic internal preloading approach.

SoundJS accepts an array of objects that represent each audio instance, containing a src property that is the URI of the audio file. These objects can have other properties, and we use an id property as a best practice, as it can make future interactions easier.

We store the relative path to our audio assets as a variable as a best practice, which allows us to make a single change when moving the files, rather than trying to track down every individual use. Another best practice is to include both an mp3 and ogg version of your audio to give the broadest playback support possible. SoundJS enables you to do this by adding a setting the alternateExtensions property. The code will look like this:

With our audio comfortably defined in a, let's move on to loading the audio. SoundJS uses an Event model, so we can add an event listener for the fileload event. It is a best practice to add this before we begin loading the audio to avoid a race condition where audio can load from cache immediately. The second parameter of the listener is the function to call back. Once this is ready, the audio load can be kicked off using the registerSounds method. Our deceptively simple and clean code should look like this:

Playback

Once audio has been registered (via loading), it can be played anywhere with the super simple play() method. It's worth noting that the handleLoad call in the previous example will fire once for each sound we load. This example shows how to immediately play audio once it is internally preloaded:

This is it, the last step when we finally make some noise! Open up the html file in a web browser, or using your favorite localhost tool. Hear the awesome? Great job! This is what the final code should look like:

Check out sample.html provided in this tutorial's directory.

Conclusion

This wraps up the tutorial on basics and best practices, which should give you a great start. The above example will not work on all mobile devices (phones and tablets), due to security requirements that require user input to play audio. This topic is the focus of the Mobile Safe tutorial. Good places to learn more are SoundJS are the online documentation and examples in GitHub.

Hope that helps!

Related Links

  1. Download CreateJS from the Adobe CDN.
  2. Get the latest SoundJS source code, including minified versions of SoundJS and FlashAudioPlugin from GitHub.
  3. Read more about SoundJS in the online docs (also available in GitHub).
  4. Get involved in active community discussion.