Skip to content

Instantly share code, notes, and snippets.

@lTyl
Created January 1, 2022 08:48
Show Gist options
  • Save lTyl/a314e72f384ca58f7b7fe398068613eb to your computer and use it in GitHub Desktop.
Save lTyl/a314e72f384ca58f7b7fe398068613eb to your computer and use it in GitHub Desktop.
Simple script which can be used to update the state of an object (like animation) depending on AudioSource outout
using System;
using System.Collections;
using UnityEngine;
namespace SMS.Tools
{
public class AudioSampleData
{
public float rootMeanSquared;
public float decibalValue;
}
public class AudioSampler : MonoBehaviour
{
[SerializeField] private int minDbClamp = -75;
[SerializeField] private int maxDbClamp = 75;
[SerializeField] private int samples = 256; // samples / audioSampleRate = seconds (256 / 48000) = 5.3ms
[SerializeField] private float dbReference = 0.1f;
[SerializeField] private int sampleThreshold = -15;
[SerializeField] private AudioSource audioSource;
private float[] workingSamples;
private bool isTalking = false;
private void Start()
{
workingSamples = new float[samples];
}
private void Update()
{
if (audioSource == null) return;
AudioSampleData data = Sample(audioSource);
if (data.decibalValue < sampleThreshold && isTalking)
{
// Not enough sound from AudioSource. Play idle animation.
isTalking = false;
}
else if (!isTalking)
{
// Sound from AudioSource. Portrait is now talking.
isTalking = true;
}
Debug.Log($"dB: {data.decibalValue}. RMS: {data.rootMeanSquared}");
}
public AudioSampleData Sample(AudioSource source)
{
source.GetOutputData(workingSamples, 0);
float sum = 0;
for (var i = 0; i < samples; i++) { sum += workingSamples[i] * workingSamples[i]; }
float rms = Mathf.Sqrt(sum / samples);
float db = 20 * Mathf.Log10(rms / dbReference);
if (db < minDbClamp) { db = minDbClamp; }
if (db > maxDbClamp) { db = maxDbClamp; }
return new AudioSampleData
{
rootMeanSquared = rms,
decibalValue = db
};
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment