diff --git a/src/Audio/AudioDevice.cs b/src/Audio/AudioDevice.cs index aec8b72..84978e8 100644 --- a/src/Audio/AudioDevice.cs +++ b/src/Audio/AudioDevice.cs @@ -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> resources = new List>(); private readonly List> streamingSounds = new List>(); + 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); diff --git a/src/Game.cs b/src/Game.cs index b148d44..56b2cf9 100644 --- a/src/Game.cs +++ b/src/Game.cs @@ -168,9 +168,8 @@ namespace MoonWorks while (accumulatedUpdateTime >= Timestep) { Inputs.Update(); - AudioDevice.Update(); - Update(Timestep); + AudioDevice.WakeThread(); accumulatedUpdateTime -= Timestep; }