Precise metronome problem

Hi guys, i have been having a problem for a while now. I have made a simple android beat machine that plays audioclips on specific intervals. I can not get the intervals to be precise and consistent. I tried this: cubeslam.net and also this: http://nodgez.net/?p=153

Using coroutines or fixedupdate while calculating time between beats prooves to be inacurate as soon as anything else happens in the scene, as well as if left running for more than a few seconds. I found a unity metronome here: Unity - Scripting API: AudioSettings.dspTime , that uses AudioSettings.dspTime, which seems to work, but i can not make it trigger audioclips.

current best version of the metronome, which tends to slow down or make errors often.

IEnumerator PlaySounds()
{
    isPlaying = true;
    while (isPlaying)
    {
        if (interval <= 0)
        {
            myAudio.PlayOneShot(myAudioClip, 1f);
            interval = (60f / BPM);
            interval -= Time.deltaTime;
        }
        else {
            interval -= Time.deltaTime;
        }
        yield return null;
    }
}

Can anybody suggest a better approach or even has a method of using the unity metronome, linked above, to time my sounds? Running Unity version 5.3.2f1 on Windows 10.

Thanks alot for your help!

The last link (Unity docs one) doesn’t work for me…

As for how to make your current code better. Sinse you want to play audio on the tick, threads are not really an option as they can’t call Uniy code… So ye, I believe coroutines or update are indeed your best option. However they will obviously not work very well when you do a lot of other things in the scene that affect your fps in a negative way. As they al run on the same thread and your metronome simply has to wait untill the rest of your code (Update etc. of other gameobjects), Unity overhead and perhaps rendering(not sure) is finished. If it is supposed to tick while it is waiting, then this one tick will be delayed. So the more other things you are doing, the higher the chance is that your metronome will be late.

You might however get an improvement by changing your code slightly to this:

IEnumerator PlaySounds()
{
    isPlaying = true;
    while (isPlaying)
    {
        if (interval <= 0)
        {
            myAudio.PlayOneShot(myAudioClip, 1f);
            interval += (60f / BPM);
        }
        interval -= Time.deltaTime;
        yield return null;
    }
}

By adding (60 / BPM) to the interval instead of setting the interval to it, you should get a more steady beat, as now when one beat is a millisec to late, this will be compensated at the next beat.

Also, reading the docs, this might be a way better answer. See AudioSource.PlayScheduled