change AudioDevice to run on a background thread

pull/47/head
cosmonaut 2023-03-03 10:55:58 -08:00
parent f8b14ea94f
commit f891586801
2 changed files with 32 additions and 4 deletions

View File

@ -1,6 +1,6 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
namespace MoonWorks.Audio
{
@ -29,10 +29,17 @@ namespace MoonWorks.Audio
private readonly List<WeakReference<AudioResource>> resources = new List<WeakReference<AudioResource>>();
private readonly List<WeakReference<StreamingSound>> streamingSounds = new List<WeakReference<StreamingSound>>();
private const int Step = 200;
private TimeSpan UpdateInterval;
private Thread Thread;
private AutoResetEvent WakeSignal;
private bool IsDisposed;
public unsafe AudioDevice()
{
UpdateInterval = TimeSpan.FromTicks(TimeSpan.TicksPerSecond / Step);
FAudio.FAudioCreate(out var handle, 0, FAudio.FAUDIO_DEFAULT_PROCESSOR);
Handle = handle;
@ -105,9 +112,26 @@ namespace MoonWorks.Audio
SpeedOfSound,
Handle3D
);
Logger.LogInfo("Setting up audio thread...");
WakeSignal = new AutoResetEvent(true);
Thread = new Thread(ThreadMain);
Thread.IsBackground = true;
Thread.Start();
}
internal void Update()
private void ThreadMain()
{
while (!IsDisposed)
{
ThreadMainTick();
WakeSignal.WaitOne(UpdateInterval);
}
}
private void ThreadMainTick()
{
for (var i = streamingSounds.Count - 1; i >= 0; i--)
{
@ -123,6 +147,11 @@ namespace MoonWorks.Audio
}
}
internal void WakeThread()
{
WakeSignal.Set();
}
public void SyncPlay()
{
FAudio.FAudio_CommitChanges(Handle, 1);

View File

@ -168,9 +168,8 @@ namespace MoonWorks
while (accumulatedUpdateTime >= Timestep)
{
Inputs.Update();
AudioDevice.Update();
Update(Timestep);
AudioDevice.WakeThread();
accumulatedUpdateTime -= Timestep;
}