-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWaveOut.cs
More file actions
477 lines (432 loc) · 16.5 KB
/
WaveOut.cs
File metadata and controls
477 lines (432 loc) · 16.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Threading;
namespace NAudio.Wave
{
/// <summary>
/// Represents a wave out device
/// </summary>
public class WaveOut : IWavePlayer, IWavePosition
{
private IntPtr hWaveOut;
private WaveOutBuffer[] buffers;
private IWaveProvider waveStream;
private volatile PlaybackState playbackState;
private readonly WaveInterop.WaveCallback callback;
private readonly WaveCallbackInfo callbackInfo;
private readonly object waveOutLock;
private int queuedBuffers;
private readonly SynchronizationContext syncContext;
/// <summary>
/// Indicates playback has stopped automatically
/// </summary>
public event EventHandler<StoppedEventArgs> PlaybackStopped;
/// <summary>
/// Retrieves the capabilities of a waveOut device
/// </summary>
/// <param name="devNumber">Device to test</param>
/// <returns>The WaveOut device capabilities</returns>
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;
}
/// <summary>
/// Returns the number of Wave Out devices available in the system
/// </summary>
public static Int32 DeviceCount => WaveInterop.waveOutGetNumDevs();
/// <summary>
/// Gets or sets the desired latency in milliseconds
/// Should be set before a call to Init
/// </summary>
public int DesiredLatency { get; set; }
/// <summary>
/// Gets or sets the number of buffers used
/// Should be set before a call to Init
/// </summary>
public int NumberOfBuffers { get; set; }
/// <summary>
/// Gets or sets the device number
/// Should be set before a call to Init
/// This must be between -1 and <see>DeviceCount</see> - 1.
/// -1 means stick to default device even default device is changed
/// </summary>
public int DeviceNumber { get; set; } = -1;
/// <summary>
/// Creates a default WaveOut device
/// Will use window callbacks if called from a GUI thread, otherwise function
/// callbacks
/// </summary>
public WaveOut()
: this(SynchronizationContext.Current == null ? WaveCallbackInfo.FunctionCallback() : WaveCallbackInfo.NewWindow())
{
}
/// <summary>
/// Creates a WaveOut device using the specified window handle for callbacks
/// </summary>
/// <param name="windowHandle">A valid window handle</param>
public WaveOut(IntPtr windowHandle)
: this(WaveCallbackInfo.ExistingWindow(windowHandle))
{
}
/// <summary>
/// Opens a WaveOut device
/// </summary>
public WaveOut(WaveCallbackInfo callbackInfo)
{
syncContext = SynchronizationContext.Current;
// set default values up
DesiredLatency = 300;
NumberOfBuffers = 2;
callback = Callback;
waveOutLock = new object();
this.callbackInfo = callbackInfo;
}
/// <summary>
/// Initialises the WaveOut device
/// </summary>
/// <param name="waveProvider">WaveProvider to play</param>
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);
}
}
/// <summary>
/// Start playing the audio from the WaveStream
/// </summary>
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));
}
}
}
/// <summary>
/// Pause the audio
/// </summary>
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");
}
}
}
/// <summary>
/// Resume playing after a pause from the same position
/// </summary>
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;
}
}
/// <summary>
/// Stop and reset the WaveOut device
/// </summary>
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);
}
}
}
/// <summary>
/// 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)
/// </summary>
/// <returns>Position in bytes</returns>
public long GetPosition() => WaveOutUtils.GetPositionBytes(hWaveOut, waveOutLock);
/// <summary>
/// Gets a <see cref="Wave.WaveFormat"/> instance indicating the format the hardware is using.
/// </summary>
public WaveFormat OutputWaveFormat => waveStream.WaveFormat;
/// <summary>
/// Playback State
/// </summary>
public PlaybackState PlaybackState => playbackState;
/// <summary>
/// Volume for this device 1.0 is full scale
/// </summary>
public float Volume
{
get
{
return WaveOutUtils.GetWaveOutVolume(hWaveOut, waveOutLock);
}
set
{
WaveOutUtils.SetWaveOutVolume(value, hWaveOut, waveOutLock);
}
}
#region Dispose Pattern
/// <summary>
/// Closes this WaveOut device
/// </summary>
public void Dispose()
{
GC.SuppressFinalize(this);
Dispose(true);
}
/// <summary>
/// Closes the WaveOut device and disposes of buffers
/// </summary>
/// <param name="disposing">True if called from <see>Dispose</see></param>
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();
}
}
/// <summary>
/// Finalizer. Only called when user forgets to call <see>Dispose</see>
/// </summary>
~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);
}
}
}
}
public class WaveCallbackInfo
{
/// <summary>
/// Callback Strategy
/// </summary>
public WaveCallbackStrategy Strategy { get; private set; }
/// <summary>
/// Window Handle (if applicable)
/// </summary>
public IntPtr Handle { get; private set; }
/// <summary>
/// Sets up a new WaveCallbackInfo for function callbacks
/// </summary>
public static WaveCallbackInfo FunctionCallback()
{
return new WaveCallbackInfo(WaveCallbackStrategy.FunctionCallback, IntPtr.Zero);
}
/// <summary>
/// Sets up a new WaveCallbackInfo to use a New Window
/// IMPORTANT: only use this on the GUI thread
/// </summary>
public static WaveCallbackInfo NewWindow()
{
return new WaveCallbackInfo(WaveCallbackStrategy.NewWindow, IntPtr.Zero);
}
/// <summary>
/// Sets up a new WaveCallbackInfo to use an existing window
/// IMPORTANT: only use this on the GUI thread
/// </summary>
public static WaveCallbackInfo ExistingWindow(IntPtr handle)
{
if (handle == IntPtr.Zero)
{
throw new ArgumentException("Handle cannot be zero");
}
return new WaveCallbackInfo(WaveCallbackStrategy.ExistingWindow, handle);
}
private WaveCallbackInfo(WaveCallbackStrategy strategy, IntPtr handle)
{
this.Strategy = strategy;
this.Handle = handle;
}
internal MmResult WaveOutOpen(out IntPtr waveOutHandle, int deviceNumber, WaveFormat waveFormat, WaveInterop.WaveCallback callback)
{
MmResult result;
if (Strategy == WaveCallbackStrategy.FunctionCallback)
{
result = WaveInterop.waveOutOpen(out waveOutHandle, (IntPtr)deviceNumber, waveFormat, callback, IntPtr.Zero, WaveInterop.WaveInOutOpenFlags.CallbackFunction);
}
else
{
result = WaveInterop.waveOutOpenWindow(out waveOutHandle, (IntPtr)deviceNumber, waveFormat, this.Handle, IntPtr.Zero, WaveInterop.WaveInOutOpenFlags.CallbackWindow);
}
return result;
}
internal MmResult WaveInOpen(out IntPtr waveInHandle, int deviceNumber, WaveFormat waveFormat, WaveInterop.WaveCallback callback)
{
MmResult result;
if (Strategy == WaveCallbackStrategy.FunctionCallback)
{
result = WaveInterop.waveInOpen(out waveInHandle, (IntPtr)deviceNumber, waveFormat, callback, IntPtr.Zero, WaveInterop.WaveInOutOpenFlags.CallbackFunction);
}
else
{
result = WaveInterop.waveInOpenWindow(out waveInHandle, (IntPtr)deviceNumber, waveFormat, this.Handle, IntPtr.Zero, WaveInterop.WaveInOutOpenFlags.CallbackWindow);
}
return result;
}
internal void Disconnect()
{
}
}
}