using System; using System.Diagnostics; using System.Threading; namespace Susurrus.XAudio2.UnitTests { /// /// A loaded module, which needs a machine that has XAudio2 and an audio device. /// public class TestModule : IDisposable { public XAudio2Module Module { get; } private TestModule(XAudio2Module module) { this.Module = module; } /// /// Returns the loaded module, or null on a machine that can't play sound. /// public static TestModule Open(int monoVoiceCount = 4, int stereoVoiceCount = 4) { XAudio2Module module = new XAudio2Module(monoVoiceCount, stereoVoiceCount); if (!module.IsSupported) { return null; } module.Load(); return new TestModule(module); } /// /// Calls Update until is true, and returns false if it never is. /// public bool UpdateUntil(Func done) { Stopwatch clock = Stopwatch.StartNew(); while (!done()) { if (clock.ElapsedMilliseconds > 5000) { return false; } Thread.Sleep(1); Module.Update(); } return true; } /// /// Calls Update until has stopped playing, and returns false if it never does. /// public bool UpdateUntilFinished(Voice voice) { return UpdateUntil(() => !Module.IsPlaying(voice)); } /// /// Calls Update until the engine plays at , which it takes up /// a moment after the call that sets it. Returns false if it never does. /// public bool UpdateUntilPitch(Voice voice, float pitch) { return UpdateUntil(() => Module.PitchOf(voice) == pitch); } /// /// Calls Update until a sound can start again, and returns None if it never can. /// public Voice UpdateUntilPlayable(Sound sound) { Stopwatch clock = Stopwatch.StartNew(); while (clock.ElapsedMilliseconds < 5000) { Module.Update(); Voice voice = Module.Play(sound, volume: 0f); if (!voice.IsNone) { return voice; } Thread.Sleep(1); } return Voice.None; } public void Dispose() { Module.Unload(); } } }