using System; using System.Runtime.InteropServices; using System.Diagnostics; using System.Threading; namespace NAudio.Wave { /// /// Represents a wave out device /// public class WaveOut : IWavePlayer, IWavePosition { private IntPtr hWaveOut; private WaveOutBuffer[] buffers; private IWaveProvider waveStream; private volatile PlaybackState playbackState; private readonly WaveInterop.WaveCallback callback; private float volume = 1; private readonly WaveCallbackInfo callbackInfo; private readonly object waveOutLock; private int queuedBuffers; private readonly SynchronizationContext syncContext; /// /// Indicates playback has stopped automatically /// public event EventHandler PlaybackStopped; /// /// Retrieves the capabilities of a waveOut device /// /// Device to test /// The WaveOut device capabilities public static WaveOutCapabilities GetCapabilities(int devNumber) { var caps = new WaveOutCapabilities(); var structSize = Marshal.SizeOf(caps); MmException.Try(WaveInterop.waveOutGetDevCaps((IntPtr)devNumber, out caps, structSize), "waveOutGetDevCaps"); return caps; } /// /// Returns the number of Wave Out devices available in the system /// public static Int32 DeviceCount => WaveInterop.waveOutGetNumDevs(); /// /// Gets or sets the desired latency in milliseconds /// Should be set before a call to Init /// public int DesiredLatency { get; set; } /// /// Gets or sets the number of buffers used /// Should be set before a call to Init /// public int NumberOfBuffers { get; set; } /// /// Gets or sets the device number /// Should be set before a call to Init /// This must be between -1 and DeviceCount - 1. /// -1 means stick to default device even default device is changed /// public int DeviceNumber { get; set; } = -1; /// /// Creates a default WaveOut device /// Will use window callbacks if called from a GUI thread, otherwise function /// callbacks /// public WaveOut() : this(SynchronizationContext.Current == null ? WaveCallbackInfo.FunctionCallback() : WaveCallbackInfo.NewWindow()) { } /// /// Creates a WaveOut device using the specified window handle for callbacks /// /// A valid window handle public WaveOut(IntPtr windowHandle) : this(WaveCallbackInfo.ExistingWindow(windowHandle)) { } /// /// Opens a WaveOut device /// public WaveOut(WaveCallbackInfo callbackInfo) { syncContext = SynchronizationContext.Current; // set default values up DesiredLatency = 300; NumberOfBuffers = 2; callback = Callback; waveOutLock = new object(); this.callbackInfo = callbackInfo; callbackInfo.Connect(callback); } /// /// Initialises the WaveOut device /// /// WaveProvider to play public void Init(IWaveProvider waveProvider) { waveStream = waveProvider; int bufferSize = waveProvider.WaveFormat.ConvertLatencyToByteSize((DesiredLatency + NumberOfBuffers - 1) / NumberOfBuffers); MmResult result; lock (waveOutLock) { result = callbackInfo.WaveOutOpen(out hWaveOut, DeviceNumber, waveStream.WaveFormat, callback); } MmException.Try(result, "waveOutOpen"); buffers = new WaveOutBuffer[NumberOfBuffers]; playbackState = PlaybackState.Stopped; for (int n = 0; n < NumberOfBuffers; n++) { buffers[n] = new WaveOutBuffer(hWaveOut, bufferSize, waveStream, waveOutLock); } } /// /// Start playing the audio from the WaveStream /// public void Play() { if (playbackState == PlaybackState.Stopped) { playbackState = PlaybackState.Playing; Debug.Assert(queuedBuffers == 0, "Buffers already queued on play"); EnqueueBuffers(); } else if (playbackState == PlaybackState.Paused) { EnqueueBuffers(); Resume(); playbackState = PlaybackState.Playing; } } private void EnqueueBuffers() { for (int n = 0; n < NumberOfBuffers; n++) { if (!buffers[n].InQueue) { if (buffers[n].OnDone()) { Interlocked.Increment(ref queuedBuffers); } else { playbackState = PlaybackState.Stopped; break; } //Debug.WriteLine(String.Format("Resume from Pause: Buffer [{0}] requeued", n)); } else { //Debug.WriteLine(String.Format("Resume from Pause: Buffer [{0}] already queued", n)); } } } /// /// Pause the audio /// public void Pause() { if (playbackState == PlaybackState.Playing) { MmResult result; playbackState = PlaybackState.Paused; // set this here, to avoid a deadlock with some drivers lock (waveOutLock) { result = WaveInterop.waveOutPause(hWaveOut); } if (result != MmResult.NoError) { throw new MmException(result, "waveOutPause"); } } } /// /// Resume playing after a pause from the same position /// public void Resume() { if (playbackState == PlaybackState.Paused) { MmResult result; lock (waveOutLock) { result = WaveInterop.waveOutRestart(hWaveOut); } if (result != MmResult.NoError) { throw new MmException(result, "waveOutRestart"); } playbackState = PlaybackState.Playing; } } /// /// Stop and reset the WaveOut device /// public void Stop() { if (playbackState != PlaybackState.Stopped) { // in the call to waveOutReset with function callbacks // some drivers will block here until OnDone is called // for every buffer playbackState = PlaybackState.Stopped; // set this here to avoid a problem with some drivers whereby MmResult result; lock (waveOutLock) { result = WaveInterop.waveOutReset(hWaveOut); } if (result != MmResult.NoError) { throw new MmException(result, "waveOutReset"); } // with function callbacks, waveOutReset will call OnDone, // and so PlaybackStopped must not be raised from the handler // we know playback has definitely stopped now, so raise callback if (callbackInfo.Strategy == WaveCallbackStrategy.FunctionCallback) { RaisePlaybackStoppedEvent(null); } } } /// /// Gets the current position in bytes from the wave output device. /// (n.b. this is not the same thing as the position within your reader /// stream - it calls directly into waveOutGetPosition) /// /// Position in bytes public long GetPosition() { lock (waveOutLock) { MmTime mmTime = new MmTime(); mmTime.wType = MmTime.TIME_BYTES; // request results in bytes, TODO: perhaps make this a little more flexible and support the other types? MmException.Try(WaveInterop.waveOutGetPosition(hWaveOut, out mmTime, Marshal.SizeOf(mmTime)), "waveOutGetPosition"); if (mmTime.wType != MmTime.TIME_BYTES) throw new Exception(string.Format("waveOutGetPosition: wType -> Expected {0}, Received {1}", MmTime.TIME_BYTES, mmTime.wType)); return mmTime.cb; } } /// /// Gets a instance indicating the format the hardware is using. /// public WaveFormat OutputWaveFormat => waveStream.WaveFormat; /// /// Playback State /// public PlaybackState PlaybackState => playbackState; /// /// Volume for this device 1.0 is full scale /// public float Volume { get => volume; set { SetWaveOutVolume(value, hWaveOut, waveOutLock); volume = value; } } internal static void SetWaveOutVolume(float value, IntPtr hWaveOut, object lockObject) { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), "Volume must be between 0.0 and 1.0"); if (value > 1) throw new ArgumentOutOfRangeException(nameof(value), "Volume must be between 0.0 and 1.0"); float left = value; float right = value; int stereoVolume = (int) (left*0xFFFF) + ((int) (right*0xFFFF) << 16); MmResult result; lock (lockObject) { result = WaveInterop.waveOutSetVolume(hWaveOut, stereoVolume); } MmException.Try(result, "waveOutSetVolume"); } #region Dispose Pattern /// /// Closes this WaveOut device /// public void Dispose() { GC.SuppressFinalize(this); Dispose(true); } /// /// Closes the WaveOut device and disposes of buffers /// /// True if called from Dispose protected void Dispose(bool disposing) { Stop(); if (disposing) { if (buffers != null) { for (int n = 0; n < buffers.Length; n++) { if (buffers[n] != null) { buffers[n].Dispose(); } } buffers = null; } } lock (waveOutLock) { WaveInterop.waveOutClose(hWaveOut); } if (disposing) { callbackInfo.Disconnect(); } } /// /// Finalizer. Only called when user forgets to call Dispose /// ~WaveOut() { System.Diagnostics.Debug.Assert(false, "WaveOut device was not closed"); Dispose(false); } #endregion // made non-static so that playing can be stopped here private void Callback(IntPtr hWaveOut, WaveInterop.WaveMessage uMsg, IntPtr dwInstance, WaveHeader wavhdr, IntPtr dwReserved) { if (uMsg == WaveInterop.WaveMessage.WaveOutDone) { GCHandle hBuffer = (GCHandle)wavhdr.userData; WaveOutBuffer buffer = (WaveOutBuffer)hBuffer.Target; Interlocked.Decrement(ref queuedBuffers); Exception exception = null; // check that we're not here through pressing stop if (PlaybackState == PlaybackState.Playing) { // to avoid deadlocks in Function callback mode, // we lock round this whole thing, which will include the // reading from the stream. // this protects us from calling waveOutReset on another // thread while a WaveOutWrite is in progress lock (waveOutLock) { try { if (buffer.OnDone()) { Interlocked.Increment(ref queuedBuffers); } } catch (Exception e) { // one likely cause is soundcard being unplugged exception = e; } } } if (queuedBuffers == 0) { if (callbackInfo.Strategy == WaveCallbackStrategy.FunctionCallback && playbackState == Wave.PlaybackState.Stopped) { // the user has pressed stop // DO NOT raise the playback stopped event from here // since on the main thread we are still in the waveOutReset function // Playback stopped will be raised elsewhere } else { playbackState = PlaybackState.Stopped; // set explicitly for when we reach the end of the audio RaisePlaybackStoppedEvent(exception); } } } } private void RaisePlaybackStoppedEvent(Exception e) { var handler = PlaybackStopped; if (handler != null) { if (syncContext == null) { handler(this, new StoppedEventArgs(e)); } else { syncContext.Post(state => handler(this, new StoppedEventArgs(e)), null); } } } } }