(Unity) HowTo : Advanced Audio Layering in Unity
Audio “horizontal layering” is a technique wherein we cut a piece of music into several layers…
- The topmost melody (piano)
- The background bass (guitar)
- The Rhythm (drums)
- etc
Then fade these layers in, or take them out, in response to circumtances of the game. This technique can be seen clearly in the Staff game, wherein a heated exchange with Worma (the player’s writing partner) causes the background music to introduce ever-more-stress-inducing layers, before removing them as the exchange calms down. (this video – skip to 2:55)
Splitting these layers up into different files may be easily done in a DAW like garageband or Ableton (just export each layer as its own audio file). However, we need a way to play these files and request a certain volume level from them. The following tutorial introduces several ways to control music layers.
NOTE : when you export a layer, make sure that each layer has the exact same duration, otherwise when a layer’s audio file loops back to the start, the layers will become desyncronized and produce a cacophony that irritates.
Yarn Command : play_audio_track
The play_audio_track yarn command will allow you to specify the name of an audio file to play, and set its volume. If the audio file is already playing, then only the volume will change. If you wish to stop the audio from playing, you may do so by requesting a volume of 0.
NOTE : You can only refer to an audio file if it is in the topmost level of a “Resources” folder. Your project likely already has one, so be sure to drag your file into it.
In order to perform layering, you should launch every audio file representing a layer at the same time, and with a volume of 0. This ensures that each audio layer begins playing simultaneously (staying in sync). The below example shows the beginning of the staff game dialogue yarn file (which you can see in the uarts staff game video a section above here). Four audio files placed into a “Resources” folder (files gameshow_layer_1 to gameshow_layer_4) are launched at the same time at a volume of 0.0. As the scene progresses, we change the volume of each track to bring them in and out, creating an impactful layering effect.
uScript Node : play_audio_track
In order to get this new node, download and import this unitypackage into your project.
This new “play audio track” node takes an audio file name (sans extension) and a number for volume between 0 and 1.
CSharp Code : YarnCommands.PlayAudioTrack function
In order to get this new function, download and import this unitypackage into your project.
Use the YarnCommands.PlayAudioTrack function (which takes a string representing the audio file name, and a float between 0 and 1 representing the desired volume).