Tutorial

This browser does not have a Java Plug-in.
Get the latest Java Plug-in here.

Sound effects - Playing audio files during animations Reload page to restart example
In this example SoundCipher loads an audio file and plays it at collision points in a simple animation. SoundCipher uses the AudioClip facility of Java to load the sound into memory so that playback is quite efficient. In fact you can even avoid some code by using sc.playAudioClip("bounce.wav") and avoid loading the sample beforehand - but it is less elegant. Most of the code is dedicated to managing the animation.



Firstly, the SoundCipher library is opened and instantiated (lines 1 & 2). Some class variables are declared next, starting with an AudioClip object called bounce, followed by a boolean flag called hit that is used to prevent double playing of the audio file when two collissions occour is quick succession. A number of floats are declared for various animation variables including ball location, size and velocity.

The setup() method loads the audio file into the AudioClip. Note that SoundCipher only supports loading of .wav and .aif audio file formats (more on this and other limitations - and solutions for them - later).

The draw() method does most of the work. It animates the ball around the display and does collision detection with the edges of the display area. When a collision is detected SoundCipher plays the audio clip.

All good. Now the bad news :(

There are numerous limitations to SoundCipher's audio features, including the limited range of supported audio file formats and the fact that SoundCipher audio functions do not work reliably when Processing sketches are exported as Java Applets.

Now the good news :)

Processing already has a decent audio library called Minim which has overcome these problems. So, rather than resolving them again it is easiest to use Minim for audio playback as shown in the reworked example below. Minim comes with the Processing distribution (as of version 1.0) so it should be easy to access.

There are other tutorials that show how SoundCipher and Mimim can be integrated to do great music and sound activities and in particular how SoundCipher's music scheduling functions can be used to control the timing of Minim in musically intuitive ways. For now, below is the same Processing sketch shown above using Minim rather than SoundCipher for audio.



The first few lines load and instantiate the Minim library and setup a Minim AudioSample object called bounce.

The setup() method loads the audio file into memory accessible by the bounce variable.

On collissions, which are detected within the draw() method, the bounce.trigger() command plays back the audio.

Mimim uses a stop() method, which is called when you halt a Processing sketch, to tidy up some of its open resources.