What are Playback States in FMOD?
FMOD’s Playback States allow us to get the playback state of an event. Is the event currently playing? Is the event currently starting or stopping? Is the event pausing at a sustain point?
Download the Unity & FMOD project for this tutorial. If you get any errors after opening the project, please delete the FMODStudioCache.asset file, as it will still contain the old path to the FMOD Studio Project.
The playback states are especially useful if we want to avoid that a sound is played twice because of some erroneous states for example.
As always, we first declare an FMOD EventInstance and a string with the path to the event that we select in the inspector:
private FMOD.Studio.EventInstance instance;
[FMODUnity.EventRef]
public string fmodEvent;
We create a method that declares an EventInstance as a parameter and let us return the PLAYBACK_STATE
of the instance:
FMOD.Studio.PLAYBACK_STATE PlaybackState(FMOD.Studio.EventInstance instance)
{
FMOD.Studio.PLAYBACK_STATE pS;
instance.getPlaybackState(out pS);
return pS;
}
As briefly described above, a simple application is to check whether an instance has already been played. In Unity’s Update() method we play an instance by pressing the space bar and stop it with the left control key. This time we check whether the instance is already playing thanks to PlaybackState()
:
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
if (PlaybackState(instance) != FMOD.Studio.PLAYBACK_STATE.PLAYING)
{
instance = FMODUnity.RuntimeManager.CreateInstance(fmodEvent);
instance.start();
}
else
{
Debug.Log("Instance is already playing!");
}
}
if (Input.GetKeyDown(KeyCode.LeftControl))
{
if (PlaybackState(instance) == FMOD.Studio.PLAYBACK_STATE.PLAYING)
{
instance.stop(FMOD.Studio.STOP_MODE.ALLOWFADEOUT);
instance.release();
}
else
{
Debug.Log("Instance is not playing!");
}
}
}
Similarly, we can use the Playback States to determine whether the instance is currently in sustain mode:
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
if (PlaybackState(instance) != FMOD.Studio.PLAYBACK_STATE.PLAYING && PlaybackState(instance) != FMOD.Studio.PLAYBACK_STATE.SUSTAINING)
{
instance = FMODUnity.RuntimeManager.CreateInstance(fmodEvent);
instance.start();
}
else if (PlaybackState(instance) == FMOD.Studio.PLAYBACK_STATE.SUSTAINING)
{
instance.triggerCue();
}
else
{
Debug.Log("Instance is already playing!");
}
}
}
I added a canvas to visualize the information about the playback state in the attached Unity Project: