Skip to content

Instantly share code, notes, and snippets.

@WillYuum
Last active December 20, 2022 01:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WillYuum/342a5c33e6bde2e49c036cab7ef15604 to your computer and use it in GitHub Desktop.
Save WillYuum/342a5c33e6bde2e49c036cab7ef15604 to your computer and use it in GitHub Desktop.

BeatDetector

What is BeatDetector?

Supposed to handle accessing audio and detecting beats in it in Unity.

using UnityEngine;
public class BeatDetector : MonoBehaviour
{
public AudioSource audioSource;
public float beatThreshold = 0.2f;
private float[] samples;
private float previousVolume;
void Start()
{
// Initialize the samples array
samples = new float[audioSource.clip.samples];
audioSource.clip.GetData(samples, 0);
}
void Update()
{
// Get the current volume of the audio
float currentVolume = GetVolume();
// If the current volume is greater than the beat threshold
// and the previous volume was below the beat threshold,
// a beat has been detected
if (currentVolume > beatThreshold && previousVolume <= beatThreshold)
{
// Do something in response to the beat (e.g. trigger an animation or action)
}
// Update the previous volume
previousVolume = currentVolume;
}
// Returns the current volume of the audio
private float GetVolume()
{
// Get the current position of the audio playback
int currentSample = (int)(audioSource.time * audioSource.clip.frequency);
// Calculate the average volume of the audio over the previous 0.1 seconds
float sum = 0;
for (int i = currentSample - (int)(audioSource.clip.frequency * 0.1f); i < currentSample; i++)
{
sum += Mathf.Abs(samples[i]);
}
return sum / (audioSource.clip.frequency * 0.1f);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment