soundvision/UnityProject/Assets/Scenes/Examples/Example1/script/RmsAnalyzer.cs

32 lines
757 B
C#
Raw Normal View History

2019-08-17 15:47:01 +00:00
using System.Linq;
using UnityEngine;
namespace Scenes.Examples.Example1.script
{
public class RmsAnalyzer : MonoBehaviour
{
[SerializeField] private AudioSource audioSource = default;
private const int BufSize = 256;
private float[] audioSamples_;
private float rms_;
public float RMS => rms_;
private void Start()
{
audioSamples_ = new float[BufSize];
}
private void Update()
{
audioSource.GetOutputData(audioSamples_, 0);
rms_ = GetRms(audioSamples_);
}
private static float GetRms(float[] buffer)
{
return Mathf.Sqrt(buffer.Sum(sample => sample * sample) / BufSize);
}
}
}