forked from naudio/NAudio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWaveInEvent.cs
283 lines (254 loc) · 9.14 KB
/
WaveInEvent.cs
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
using System;
using System.Runtime.InteropServices;
using NAudio.Mixer;
using System.Threading;
using NAudio.CoreAudioApi;
// ReSharper disable once CheckNamespace
namespace NAudio.Wave
{
/// <summary>
/// Recording using waveIn api with event callbacks.
/// Use this for recording in non-gui applications
/// Events are raised as recorded buffers are made available
/// </summary>
public class WaveInEvent : IWaveIn
{
private readonly AutoResetEvent callbackEvent;
private readonly SynchronizationContext syncContext;
private IntPtr waveInHandle;
private volatile CaptureState captureState;
private WaveInBuffer[] buffers;
/// <summary>
/// Indicates recorded data is available
/// </summary>
public event EventHandler<WaveInEventArgs> DataAvailable;
/// <summary>
/// Indicates that all recorded data has now been received.
/// </summary>
public event EventHandler<StoppedEventArgs> RecordingStopped;
/// <summary>
/// Prepares a Wave input device for recording
/// </summary>
public WaveInEvent()
{
callbackEvent = new AutoResetEvent(false);
syncContext = SynchronizationContext.Current;
DeviceNumber = 0;
WaveFormat = new WaveFormat(8000, 16, 1);
BufferMilliseconds = 100;
NumberOfBuffers = 3;
captureState = CaptureState.Stopped;
}
/// <summary>
/// Returns the number of Wave In devices available in the system
/// </summary>
public static int DeviceCount => WaveInterop.waveInGetNumDevs();
/// <summary>
/// Retrieves the capabilities of a waveIn device
/// </summary>
/// <param name="devNumber">Device to test</param>
/// <returns>The WaveIn device capabilities</returns>
public static WaveInCapabilities GetCapabilities(int devNumber)
{
WaveInCapabilities caps = new WaveInCapabilities();
int structSize = Marshal.SizeOf(caps);
MmException.Try(WaveInterop.waveInGetDevCaps((IntPtr)devNumber, out caps, structSize), "waveInGetDevCaps");
return caps;
}
/// <summary>
/// Milliseconds for the buffer. Recommended value is 100ms
/// </summary>
public int BufferMilliseconds { get; set; }
/// <summary>
/// Number of Buffers to use (usually 2 or 3)
/// </summary>
public int NumberOfBuffers { get; set; }
/// <summary>
/// The device number to use
/// </summary>
public int DeviceNumber { get; set; }
private void CreateBuffers()
{
// Default to three buffers of 100ms each
int bufferSize = BufferMilliseconds * WaveFormat.AverageBytesPerSecond / 1000;
if (bufferSize % WaveFormat.BlockAlign != 0)
{
bufferSize -= bufferSize % WaveFormat.BlockAlign;
}
buffers = new WaveInBuffer[NumberOfBuffers];
for (int n = 0; n < buffers.Length; n++)
{
buffers[n] = new WaveInBuffer(waveInHandle, bufferSize);
}
}
private void OpenWaveInDevice()
{
CloseWaveInDevice();
MmResult result = WaveInterop.waveInOpenWindow(out waveInHandle, (IntPtr)DeviceNumber, WaveFormat,
callbackEvent.SafeWaitHandle.DangerousGetHandle(),
IntPtr.Zero, WaveInterop.WaveInOutOpenFlags.CallbackEvent);
MmException.Try(result, "waveInOpen");
CreateBuffers();
}
/// <summary>
/// Start recording
/// </summary>
public void StartRecording()
{
if (captureState != CaptureState.Stopped)
throw new InvalidOperationException("Already recording");
OpenWaveInDevice();
MmException.Try(WaveInterop.waveInStart(waveInHandle), "waveInStart");
captureState = CaptureState.Starting;
ThreadPool.QueueUserWorkItem((state) => RecordThread(), null);
}
private void RecordThread()
{
Exception exception = null;
try
{
DoRecording();
}
catch (Exception e)
{
exception = e;
}
finally
{
captureState = CaptureState.Stopped;
RaiseRecordingStoppedEvent(exception);
}
}
private void DoRecording()
{
captureState = CaptureState.Capturing;
foreach (var buffer in buffers)
{
if (!buffer.InQueue)
{
buffer.Reuse();
}
}
while (captureState == CaptureState.Capturing)
{
if (callbackEvent.WaitOne())
{
// requeue any buffers returned to us
foreach (var buffer in buffers)
{
if (buffer.Done)
{
if (buffer.BytesRecorded > 0)
{
DataAvailable?.Invoke(this, new WaveInEventArgs(buffer.Data, buffer.BytesRecorded));
}
if (captureState == CaptureState.Capturing)
{
buffer.Reuse();
}
}
}
}
}
}
private void RaiseRecordingStoppedEvent(Exception e)
{
var handler = RecordingStopped;
if (handler != null)
{
if (syncContext == null)
{
handler(this, new StoppedEventArgs(e));
}
else
{
syncContext.Post(state => handler(this, new StoppedEventArgs(e)), null);
}
}
}
/// <summary>
/// Stop recording
/// </summary>
public void StopRecording()
{
if (captureState != CaptureState.Stopped)
{
captureState = CaptureState.Stopping;
MmException.Try(WaveInterop.waveInStop(waveInHandle), "waveInStop");
//Reset, triggering the buffers to be returned
MmException.Try(WaveInterop.waveInReset(waveInHandle), "waveInReset");
callbackEvent.Set(); // signal the thread to exit
}
}
/// <summary>
/// Gets the current position in bytes from the wave input device.
/// it calls directly into waveInGetPosition)
/// </summary>
/// <returns>Position in bytes</returns>
public long GetPosition()
{
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.waveInGetPosition(waveInHandle, out mmTime, Marshal.SizeOf(mmTime)), "waveInGetPosition");
if (mmTime.wType != MmTime.TIME_BYTES)
throw new Exception(string.Format("waveInGetPosition: wType -> Expected {0}, Received {1}", MmTime.TIME_BYTES, mmTime.wType));
return mmTime.cb;
}
/// <summary>
/// WaveFormat we are recording in
/// </summary>
public WaveFormat WaveFormat { get; set; }
/// <summary>
/// Dispose pattern
/// </summary>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (captureState != CaptureState.Stopped)
StopRecording();
CloseWaveInDevice();
}
}
private void CloseWaveInDevice()
{
// Some drivers need the reset to properly release buffers
WaveInterop.waveInReset(waveInHandle);
if (buffers != null)
{
for (int n = 0; n < buffers.Length; n++)
{
buffers[n].Dispose();
}
buffers = null;
}
WaveInterop.waveInClose(waveInHandle);
waveInHandle = IntPtr.Zero;
}
/// <summary>
/// Microphone Level
/// </summary>
public MixerLine GetMixerLine()
{
// TODO use mixerGetID instead to see if this helps with XP
MixerLine mixerLine;
if (waveInHandle != IntPtr.Zero)
{
mixerLine = new MixerLine(waveInHandle, 0, MixerFlags.WaveInHandle);
}
else
{
mixerLine = new MixerLine((IntPtr)DeviceNumber, 0, MixerFlags.WaveIn);
}
return mixerLine;
}
/// <summary>
/// Dispose method
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}