Playing around with audio in Unity

When I was putting audio into 10 Seconds in 10 Seconds, I found it annoying that certain sounds would only play partially. This was happening because the sounds in question were being played by objects that existed for a very short amount of time.

When a GameObject gets destroyed, it’s AudioSource also gets destroyed. If that AudioSource was playing a sound, it will stop immediately when destroyed.

The usual solution to this problem would be to create a new GameObject just to play the sound you want and destroy it when done playing. There are a few problems with this solution:

  1. It’s creating and deallocating objects too often, which can cause memory fragmentation.
  2. From my experience, it’s not flexible because I could only get it to work if I made a different prefab for every sound to play.
  3. Implementing sound effects in this matter might confuse other programmers who are expecting a call to play audio as opposed to a call to instantiate a prefab.

What I wanted to do in for audio playback in Unity was to play sounds in multiple channels in the same way an audio work station used mixer software to mix audio from multiple channels. The bad news: Unity does not give you this kind of control (directly anyway). The good news, Unity can mix audio together, as long as they are being played from multiple instances of AudioSource.

With this in mind, I wanted to make a mixer that can be called from anywhere to play sound to a specific channel. The idea is you can make a call to this audio mixer to play a sound in a specific channel and label the sound as a specific audio type. The audio types would include sound, music, jingle, and voice. I also wanted playback controls based on a specific channel, all channels, or channels label with a specific audio type.

After messing around for a few days, I would like to present the AudioMixer. It’s a Unity script that allows mixing of sound in multiple channels. This can be very useful for playing reoccurring  sounds, loop music, or other audio tasks.

You can read about the AudioMixer on the AudioMixer page, or you can go straight to Github and get it. Documentation and instructions on how to use AudioMixer are provided on Github.