using System;
using System.Runtime.InteropServices;
using NAudio.Mixer;
using System.Threading;
using NAudio.CoreAudioApi;
// ReSharper disable once CheckNamespace
namespace NAudio.Wave
{
///
/// Recording using waveIn api with event callbacks.
/// Use this for recording in non-gui applications
/// Events are raised as recorded buffers are made available
///
public class WaveInEvent : IWaveIn
{
private readonly AutoResetEvent callbackEvent;
private readonly SynchronizationContext syncContext;
private IntPtr waveInHandle;
private volatile CaptureState captureState;
private WaveInBuffer[] buffers;
///
/// Indicates recorded data is available
///
public event EventHandler DataAvailable;
///
/// Indicates that all recorded data has now been received.
///
public event EventHandler RecordingStopped;
///
/// Prepares a Wave input device for recording
///
public WaveInEvent()
{
callbackEvent = new AutoResetEvent(false);
syncContext = SynchronizationContext.Current;
DeviceNumber = 0;
WaveFormat = new WaveFormat(8000, 16, 1);
BufferMilliseconds = 100;
NumberOfBuffers = 3;
captureState = CaptureState.Stopped;
}
///
/// Returns the number of Wave In devices available in the system
///
public static int DeviceCount => WaveInterop.waveInGetNumDevs();
///
/// Retrieves the capabilities of a waveIn device
///
/// Device to test
/// The WaveIn device capabilities
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;
}
///
/// Milliseconds for the buffer. Recommended value is 100ms
///
public int BufferMilliseconds { get; set; }
///
/// Number of Buffers to use (usually 2 or 3)
///
public int NumberOfBuffers { get; set; }
///
/// The device number to use
///
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();
}
///
/// Start recording
///
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)
{
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);
}
}
}
///
/// Stop recording
///
public void StopRecording()
{
if (captureState != CaptureState.Stopped)
{
captureState = CaptureState.Stopping;
callbackEvent.Set(); // signal the thread to exit
MmException.Try(WaveInterop.waveInStop(waveInHandle), "waveInStop");
}
}
///
/// WaveFormat we are recording in
///
public WaveFormat WaveFormat { get; set; }
///
/// Dispose pattern
///
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;
}
///
/// Microphone Level
///
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;
}
///
/// Dispose method
///
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}