Skip to content

Instantly share code, notes, and snippets.

@buijldert
Created April 6, 2018 11:33
Show Gist options
  • Save buijldert/36aa2ab89789310ac2bdeb94c63766f4 to your computer and use it in GitHub Desktop.
Save buijldert/36aa2ab89789310ac2bdeb94c63766f4 to your computer and use it in GitHub Desktop.
using UnityEngine;
public class AudioSourceLoudnessTester : MonoBehaviour {
public AudioSource audioSource;
public float updateStep = 0.1f;
public int sampleDataLength = 1024;
private float currentUpdateTime = 0f;
private float clipLoudness;
private float[] clipSampleData;
// Use this for initialization
void Awake () {
if (!audioSource) {
Debug.LogError(GetType() + ".Awake: there was no audioSource set.");
}
clipSampleData = new float[sampleDataLength];
}
// Update is called once per frame
void Update () {
currentUpdateTime += Time.deltaTime;
if (currentUpdateTime >= updateStep) {
currentUpdateTime = 0f;
audioSource.clip.GetData(clipSampleData, audioSource.timeSamples);
clipLoudness = 0f;
foreach (var sample in clipSampleData) {
clipLoudness += Mathf.Abs(sample);
}
clipLoudness /= sampleDataLength;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment