Skip to content

Instantly share code, notes, and snippets.

@Madhotdog
Created April 13, 2016 13:03
Show Gist options
  • Save Madhotdog/55ce628e7e8b5c02ed3cf1bf2e81e0c7 to your computer and use it in GitHub Desktop.
Save Madhotdog/55ce628e7e8b5c02ed3cf1bf2e81e0c7 to your computer and use it in GitHub Desktop.
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