AxibugEmuOnline/AxibugEmuOnline.Client/Assets/Script/NesEmulator/AudioProvider.cs

51 lines
1.4 KiB
C#
Raw Normal View History

2024-08-06 16:03:17 +08:00
using UnityEngine;
2024-08-02 16:50:16 +08:00
using VirtualNes.Core;
2024-08-06 13:49:24 +08:00
namespace AxibugEmuOnline.Client
2024-08-02 16:50:16 +08:00
{
2024-08-06 13:49:24 +08:00
public class AudioProvider : MonoBehaviour
2024-08-02 16:50:16 +08:00
{
public NesEmulator NesEmu { get; set; }
2024-08-06 16:03:17 +08:00
2024-08-06 13:49:24 +08:00
[SerializeField]
private AudioSource m_as;
2024-08-02 16:50:16 +08:00
2024-08-06 13:49:24 +08:00
private SoundBuffer _buffer = new SoundBuffer(4096);
2024-08-06 16:03:17 +08:00
public void Start()
2024-08-06 13:49:24 +08:00
{
var dummy = AudioClip.Create("dummy", 1, 1, AudioSettings.outputSampleRate, false);
2024-08-02 16:50:16 +08:00
2024-08-06 13:49:24 +08:00
dummy.SetData(new float[] { 1 }, 0);
m_as.clip = dummy; //just to let unity play the audiosource
m_as.loop = true;
m_as.spatialBlend = 1;
m_as.Play();
}
2024-08-02 16:50:16 +08:00
2024-08-06 13:49:24 +08:00
void OnAudioFilterRead(float[] data, int channels)
2024-08-02 16:50:16 +08:00
{
2024-08-06 13:49:24 +08:00
int step = channels;
2024-08-06 16:03:17 +08:00
if (NesEmu == null || NesEmu.NesCore == null) return;
ProcessSound(NesEmu.NesCore, (uint)(data.Length / channels));
2024-08-02 16:50:16 +08:00
2024-08-06 13:49:24 +08:00
for (int i = 0; i < data.Length; i += step)
{
float rawFloat = 0;
if (_buffer.TryRead(out byte rawData))
rawFloat = rawData / 255f;
2024-08-02 16:50:16 +08:00
2024-08-06 13:49:24 +08:00
data[i] = rawFloat;
for (int fill = 1; fill < step; fill++)
data[i + fill] = rawFloat;
}
2024-08-02 16:50:16 +08:00
}
2024-08-06 16:03:17 +08:00
void ProcessSound(NES nes, uint feedCount)
2024-08-06 13:49:24 +08:00
{
2024-08-06 16:03:17 +08:00
nes.apu.Process(_buffer, feedCount);
2024-08-06 13:49:24 +08:00
}
2024-08-02 16:50:16 +08:00
}
2024-08-06 13:49:24 +08:00
}