GBA.Unity/Assets/emulator/AudioProvider.cs

76 lines
1.9 KiB
C#
Raw Permalink Normal View History

2024-08-16 14:51:15 +08:00
using OptimeGBA;
using System;
using UnityEngine;
public class AudioProvider : MonoBehaviour
{
[SerializeField]
private AudioSource m_as;
private RingBuffer<float> _buffer;
private TimeSpan lastElapsed;
public double audioFPS { get; private set; }
float lastData = 0;
public void Awake()
{
2024-08-16 21:50:32 +08:00
AudioClip clip = AudioClip.Create("dummy", GbaAudio.SampleRate * 2, 2, GbaAudio.SampleRate, true);
AudioSettings.GetDSPBufferSize(out int bufferLength, out _);
_buffer = new RingBuffer<float>(bufferLength * 2 * 2);
2024-08-16 14:51:15 +08:00
m_as.clip = clip;
m_as.playOnAwake = true;
//m_as.loop = true;
m_as.spatialBlend = 1;
}
public void Initialize()
{
if (!m_as.isPlaying)
{
m_as.Play();
}
}
private void OnAudioFilterRead(float[] data, int channels)
{
int step = channels;
step = 1;
for (int i = 0; i < data.Length; i += step)
{
if (_buffer.TryRead(out float rawData))
data[i] = rawData;
else
break;
}
//int step = channels;
//step = 1;
//for (int i = 0; i < data.Length; i += step)
//{
// float rawFloat = lastData;
// if (_buffer.TryRead(out float rawData))
// {
// rawFloat = rawData;
// }
// data[i] = rawFloat;
// for (int fill = 1; fill < step; fill++)
// data[i + fill] = rawFloat;
// lastData = rawFloat;
//}
}
public void AudioReady(float[] data)
{
if (!Emulator.instance.EnableAudio) return;
var current = Emulator.sw.Elapsed;
var delta = current - lastElapsed;
lastElapsed = current;
audioFPS = 1d / delta.TotalSeconds;
for (int i = 0; i < data.Length; i++)
{
_buffer.Write(data[i]);
}
}
}