Hello,
I am trying to make an interactive music system that simply tracks a songs bpm on start and can play an audiosource clip on the beat. So for each downbeat (1,2,3,4) my music class sends out a music event which is listened for by a script which then can play from the selected AudioSource.
However, I am having problems with this system. I am providing the two classes I am using:
BPM Tracker which sends out the event and contains the logic
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class BpmTracker : MonoBehaviour
{
public int bpm;
public static event Action onBeat;
public static event Action playMusic;
private float beatInterval, beatIntervalCount = 0.1f;
private int musicCount = 0;
void Start()
{
beatInterval = 60f/(float)bpm;
}
void FixedUpdate()
{
if (beatIntervalCount <= Time.time)
{
onBeat?.Invoke();
if (musicCount == 0)
{
playMusic?.Invoke();
musicCount++;
}
beatIntervalCount = Time.time + beatInterval;
}
}
}
And this is my script for listening/playing the sounds
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Music : MonoBehaviour
{
public AudioSource kick, hat, snare, synth;
void Awake()
{
}
void FixedUpdate()
{
}
private void OnEnable()
{
BpmTracker.onBeat += kick.Play;
BpmTracker.onBeat += snare.Play;
BpmTracker.playMusic += synth.Play;
}
private void OnDisable()
{
BpmTracker.onBeat -= kick.Play;
BpmTracker.playMusic += synth.Play;
BpmTracker.onBeat += snare.Play;
}
}
This mostly works as expected but there is one critical problem. My BPM Tracker does not seem to be tracking evenly. When I hit play I can tell that the kick drum sometimes slightly speeds up and slows down. I cannot account for this behavior.
If anyone has thoughts I would really appreciate it!!!