How to control Fmod audio loop in code

How to control Fmod audio loop in code

Loop Regions are created in FMOD Studio, along with parameter or event conditions that define when to leave the loop region. Parameters can then control the loop region using EventInstance::setParameterByName if you have set it up to use parameter conditions, and if you have set it up to use event conditions then you just need to play the linked event to leave the loop.

I recommend you read through the Timeline Logic section of the FMOD Studio documentation, and load the “Documents\FMOD Studio\examples\Examples.fspro” example project in FMOD Studio to have a look at how parameters are being used to change the loop region, especially in the “Music>Level 01” and “Music>Level 03” events.

Here is a basic example of how you would then control parameter values at runtime with the “Level 01” event to change the loop points:

using UnityEngine;
using FMODUnity;

public class LoopPoints : MonoBehaviour
{
    public EventReference Event = EventReference.Find("event:/Music/Level 01");
    
    public float ProgressionParameter = 0.0f;
    public float StingerParameter = 0.0f;

    private FMOD.Studio.EventInstance _eventInstance;

    private float lastParam = 0.0f;

    void Start()
    {
        _eventInstance = RuntimeManager.CreateInstance(Event);
        _eventInstance.start();
    }

    void Update()
    {
        if(ProgressionParameter + StingerParameter != lastParam)
        {
            _eventInstance.setParameterByName("Progression", ProgressionParameter);
            _eventInstance.setParameterByName("Stinger", StingerParameter);

            lastParam = ProgressionParameter + StingerParameter;
        }
    }
}