Many Android devices exhibit varying degrees of latency when playing sound via the Unity AudioSource.
This is a well known issue and there are already several solutions out there to work around
the problem. This is generally achieved by using the Android SoundPool service. The solution offered here is no different in that regard.
The AudioPlayer.cs class provides a platform-neutral API, and two implementations — uses SoundPool on Android, and Unity AudioSource on other platforms. Compiler #if directives select which implementation to build, according to the target platform.
Download AudioPlayer.cs here. (right-click Save As.)
Project and Scene Setup
DSP Buffer Size
For best performance on iOS, the DSP Buffer Size parameter in AudioManager should be set to Best latency, which translates to a DSP Buffer Size of 256KB. When running within the Unity editor, the AudioPlayer class will check and display a warning (via Debug.Assert) if this is not the case.
Placement in Scene
Create an empty GameObject, then use Add Component to add the script AudioPlayer.cs (Audio Player).
It is ok to add more script components to this GameObject. For example, if the scene includes a sound manager class that decides when to play effects, it is possible to place that script on the same GameObject. The example provided below is one such very simple sound manager class.
Sound Files
This class expects sound files as MP3 files that reside within the StreamingAssets directory, which should be placed directly below the Assets folder.
Component Properties
NumChannels (int) determines the maximum number of effects that can play at once. Each channel can play only one sound at a time, but sounds from all channels will be mixed together. The default is 4 channels.
On Android, this value is used during the creation of the SoundPool object. On other platforms, this determines the number of Unity AudioSource objects which will be created.
For API methods that expect a channel number, specify the channel as a number between zero (0) and NumChannels.
Sound (boolean) is set to false if all sound should be muted. It is probably easier to adjust this property using the AudioPlayer.SetSound() method, which does not require a reference to the GameObject containing the AudioPlayer script component.
Using the API – Example Code
using UnityEngine; using System.Collections; public class SoundManager : MonoBehaviour { public PlayerObject player; // below constants assume the default of four channels in AudioPlayer const int firstChannel = 0; // channel zero not used in the example const int walkChannel = 1; const int pickupChannel = 2; const int introChannel = 3; bool walking; bool paused; bool intro; void Start() { AudioPlayer.SetSound(PlayerPrefs.GetInt("sound", 1) != 0); // // request to load sound effects. these must be MP3 files placed // in the StreamingAssets folder, directly below Assets folder. // AudioPlayer.Load("walk1"); AudioPlayer.Load("walk2"); AudioPlayer.Load("walk3"); AudioPlayer.Load("pickup"); AudioPlayer.Load("intro"); // // request various game objects to signal us so we know when // to play or stop playing sound effects // player.OnMove += OnPlayerMove; player.OnPickup += OnPickupCollected; // // set a flag to play level intro sound effect // intro = true; } // // signal the player is walking or stopping. player walking is // a state, not a single event, so we set a flag, and let our // Update() method continuously one of three possible effects. // // note that the code below works the same whether the signal // is sent every frame, or only when the player state really changes. // void OnPlayerMove(bool walkingOrStopped) { // // walkingOrStopped is true for started walking, false otherwise // if (walkingOrStopped) walking = true; else if (walking) { // player stopped walking, stop sound and clear our flag walking = false; AudioPlayer.Stop(walkChannel); } } // // signal that a pickup was collected. unlike movement, // this is an event rather than a state change, so we can // play the pickup effect immediately. the last parameter, // 0.5f, controls the volume -- half volume in this case. // void OnPickupCollected() { AudioPlayer.Play(pickupChannel, "pickup", 0.5f); } // // Update method, which we use // // - to manage pause/resume, and sound on/off // // - play level intro sound // // - play continuous sound effects (like walking) // void Update() { // // a frame where timeScale is zero, means the game is paused. // if it wasn't already paused, let's pause all sound. // if (Time.timeScale == 0f) { if (! paused) { paused = true; AudioPlayer.Pause(); } return; } if (paused) { // // resuming from pause, and assuming the pause screen // presents a choice to mute all sounds, which is then // stored in PlayerPrefs. // // apply the sound on/off flag to the AudioPlayer object, // then resume all sounds -- which would actually stop all // sounds if the call to SetSound() disabled all sounds. // AudioPlayer.SetSound(PlayerPrefs.GetInt("sound", 1) != 0); AudioPlayer.Resume(); paused = false; } // // if sound is muted, we have nothing further to do // if (! AudioPlayer.GetSound()) return; // // we need to play level intro sound. this demonstrates that // sounds are not immediately playable after a call to // AudioPlayer.Load(). // // we have to keep trying to play the sound, and ask AudioPlayer // if the sound really is playing. note that this effort is only // necessary for non-recurring sounds which should play soon // after the call to AudioPlayer.Load(), so typically this would // be a level intro sound. // if (intro) { if (AudioPlayer.IsPlaying(introChannel)) intro = false; else AudioPlayer.Play(introChannel, "intro"); } } // // while the player is walking, which is a continuous state, // we want to keep playing one of several walking sound // effects that we have. // if (walking && (! AudioPlayer.IsPlaying(walkChannel))) { int r = Random.Range(1, 3 + 1); string clip = "walk" + r.ToString(); AudioPlayer.Play(walkChannel, clip); } } }
API Reference
All methods are static and do not require a reference to the GameObject that contains the AudioPlayer component. They are to be invoked as (for example) AudioPlayer.Play(), as shown in the example above.
bool GetSound()
– Returns true if sound is enabled, false if sound is muted.
void SetSound(bool sound)
– Enables or mutes sound. The Play() method will not begin playing any new sounds while sound is muted. But note that calling SetSound(false) does not pause or stop any currently playing sounds.
void Load(string name)
– Makes a request to load an MP3 sound file from the StreamingAssets directory. This directory should be placed directly below the Assets folder. The .MP3 extension should not be included in this parameter, only the file name. Note that this method call returns before the sound is loaded, and the sound may not be immediately available to play. The example above shows this issue in the context of trying to play a sound at the start of a scene.
void Play(int channel, string name, float volume = 1f, bool loop = false)
– First, this stops the currently playing sound on the specified channel. Then, if sound is not muted, plays the specified sound on the channel. Volume should be a value between 0 and 1. The channel number is a number between 0 and the value set in the NumChannels property of the AudioPlayer component.
void Stop(int channel)
– Stops playing the currently playing sound on the specified channel.
bool IsPlaying(int channel)
– Returns true if sound is currently playing on the specified channel. As noted above, calling SetSound(false) does not stop sounds that are currently playing, so it is possible for this method to return true even after sound has been muted, while any previously-started sounds have not yet finished playing.
void Pause()
– Pauses all channels that are currently playing. It is not recommended to issue calls to Play() after a call to Pause() and before a matching call to Resume().
void Resume()
– Resumes play on all channels that were paused by a previous call to Pause(). Note that if SetSound(false) was called to mute sounds after pausing, then a call to this method will stop, rather than resume, all sounds that were playing prior to calling Pause(). It is not recommended to issue calls to Play() after a call to Pause() and before a matching call to Resume().
License
Public domain, free to use however you wish.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR “AS IS” AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.