BeatCounter, a Unity script used to determine timing.
using UnityEngine; | |
using System.Collections; | |
using System; | |
[RequireComponent(typeof(AudioSource))] | |
public class BeatCounter : MonoBehaviour { | |
public Action<int> BeatEvent = delegate { }; | |
public Action BarEvent = delegate { }; | |
public float bpm; | |
public int beatsPerBar; | |
public int beatOffset = 1; | |
public bool isAudioPlaying; | |
private float samplesPerBeat; | |
private int currentBeat = 0; | |
private float beatSphereSize = 0; | |
private float barSphereSize = 0; | |
// Use this for initialization | |
void OnBeat (int beatCount) { | |
beatSphereSize = 2; | |
BeatEvent(beatCount % beatsPerBar); | |
//Debug.Log(currentBeat); | |
if(beatsPerBar > 0 && (currentBeat == 0 || ((currentBeat) % beatsPerBar == 0))){ | |
OnBar(); | |
} | |
} | |
void OnBar () { | |
//Debug.Log("bar"); | |
BarEvent(); | |
barSphereSize = 2; | |
} | |
public void Reset(){ | |
currentBeat = 0; | |
isAudioPlaying = false; | |
} | |
public void StartCount(){ | |
float samplesPerMin = GetComponent<AudioSource>().clip.samples * (60f/GetComponent<AudioSource>().clip.length); | |
samplesPerBeat = samplesPerMin / bpm; | |
currentBeat = Mathf.FloorToInt(GetComponent<AudioSource>().timeSamples / samplesPerBeat); | |
isAudioPlaying = true; | |
currentBeat = beatOffset; | |
} | |
// Update is called once per frame | |
void Update () { | |
if(!isAudioPlaying && GetComponent<AudioSource>().isPlaying){ | |
StartCount(); | |
} | |
else{ | |
int newBeat = Mathf.FloorToInt(GetComponent<AudioSource>().timeSamples / samplesPerBeat) + beatOffset; | |
if(newBeat > currentBeat){ | |
currentBeat = newBeat; | |
OnBeat(currentBeat); | |
} | |
else if(newBeat < currentBeat){ | |
Debug.Log("Loop!"); | |
currentBeat = newBeat; | |
OnBeat(currentBeat); | |
} | |
} | |
barSphereSize-= 5 * Time.deltaTime; | |
if(barSphereSize < 0){ | |
barSphereSize = 0; | |
} | |
beatSphereSize-= 5 * Time.deltaTime; | |
if(beatSphereSize < 0){ | |
beatSphereSize = 0; | |
} | |
} | |
void OnDrawGizmos() { | |
Gizmos.color = Color.red; | |
Gizmos.DrawSphere(transform.position, beatSphereSize); | |
Vector3 pos = transform.position; | |
pos.x += 4; | |
Gizmos.color = Color.blue; | |
Gizmos.DrawSphere(transform.position, barSphereSize); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment