Hi everybody,
I am trying to sync animator triggers to the music of my game. The problem is, that the beats are slightly slowing down. The first beat is 58 Samples off, the second 117, the third 411 and so on…
So far, here is what I got:
using UnityEngine;
using System.Collections;
public class BeatSync : MonoBehaviour {
private AudioSource music;
private Animator animator;
private float MusicPos; //Position of the playback head from the last beat
[Tooltip("Interval of the trigger")]
public float BPM = 60;
[Tooltip("Sample Rate")]
public float SampleRate = 44100;
void Start()
{
music = GameObject.Find("Music").GetComponent<AudioSource>();
animator = GetComponent<Animator>();
StartMusic();
}
void StartMusic()
{
MusicPos = 0;
music.Play();
}
void Update()
{
if (music.timeSamples - MusicPos > SampleRate * (60 / BPM))
{
animator.SetTrigger("Beat");
MusicPos = music.timeSamples;
}
}
}
the music file settings are
Decompress on load
PCM compression
Preserve samplin rate
Is there anything wrong with it or maybe some better way to do this?