-
Notifications
You must be signed in to change notification settings - Fork 4
/
Amplitude.cs
50 lines (39 loc) · 1.32 KB
/
Amplitude.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using UnityEngine;
using System;
//https://answers.unity.com/questions/1167177/how-do-i-get-the-current-volume-level-amplitude-of.html
public class Amplitude : MonoBehaviour {
public AudioSource audioSource;
public float updateStep = 0.1f;
public int sampleDataLength = 512;
private float currentUpdateTime = 0f;
public float amplitude;
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 () {
if (audioSource.isPlaying && audioSource.time < (audioSource.clip.length - 0.2)) {
currentUpdateTime += Time.deltaTime;
if (currentUpdateTime >= updateStep) {
currentUpdateTime = 0f;
try {
audioSource.clip.GetData(clipSampleData, audioSource.timeSamples);
} catch (Exception e) {
}
//I read 1024 samples, which is about 80 ms on a 44khz stereo clip, beginning at the current sample position of the clip.
amplitude = 0f;
foreach (var sample in clipSampleData) {
amplitude += Mathf.Abs(sample);
}
amplitude /= sampleDataLength;
}
} else {
amplitude = 0f;
}
}
}