/// <summary> /// Open WaveOut. /// WaveOutを開きます。 /// </summary> /// <param name="deviceId">WaveOut.WaveMapperか、GetDeviceNames()のindex</param> /// <param name="samplesPerSec">44100 (Hz)</param> /// <param name="bitsPerSample">16 or 8</param> /// <param name="channels">2 or 1</param> public WaveOut(int deviceId, int samplesPerSec, int bitsPerSample, int channels) { Win32.WaveFormatEx wfx = new Win32.WaveFormatEx(samplesPerSec, bitsPerSample, channels); eventHandler = new MessageThread(); IntPtr ptr = new IntPtr(eventHandler.Win32ThreadID); int mmret = Win32.waveOutOpen(out deviceHandle, (uint)deviceId, ref wfx, ptr, IntPtr.Zero, Win32.CALLBACK_THREAD); if (mmret != Win32.MMSYSERR_NOERROR) { eventHandler.Dispose(); throw new Exception("デバイスが開けませんでした。(" + mmret + ")"); } eventHandler.MessageHandlers[Win32.MM_WOM_DONE] = delegate(Message m) { Win32.WaveHeader header = Win32.WaveHeader.FromIntPtr(m.LParam); WaveBuffer buf = WaveBuffer.FromWaveHeader(header); Win32.waveOutUnprepareHeader(deviceHandle, buf.pHeader, Win32.WaveHeader.SizeOfWaveHeader); Interlocked.Add(ref enqueuedBufferSize, -buf.Data.Length); buf.Dispose(); if (OnDone != null) { OnDone(); } }; }
/// <summary> /// Open WaveIn. /// WaveInを開きます。 /// </summary> /// <param name="deviceId">WaveIn.WaveMapper or index of GetDeviceNames(). WaveIn.WaveMapperか、GetDeviceNames()のindex</param> /// <param name="samplesPerSec">ex) 44100 (Hz)</param> /// <param name="bitsPerSample">16 or 8</param> /// <param name="channels">2 or 1</param> public WaveIn(int deviceId, int samplesPerSec, int bitsPerSample, int channels) { Win32.WaveFormatEx wfx = new Win32.WaveFormatEx(samplesPerSec, bitsPerSample, channels); eventHandler = new MessageThread(ThreadPriority.AboveNormal); eventHandler.MessageHandlers[Win32.MM_WIM_DATA] = delegate(Message m) { Win32.WaveHeader header = Win32.WaveHeader.FromIntPtr(m.LParam); WaveBuffer buf = WaveBuffer.FromWaveHeader(header); int bytesRecorded = (int)header.dwBytesRecorded; if (OnData != null && bytesRecorded != 0) { byte[] data = buf.Data; if (bytesRecorded != buf.Data.Length) { data = new byte[bytesRecorded]; Array.Copy(buf.Data, data, bytesRecorded); } OnData(data); } if (recording) { Win32.waveInAddBuffer(deviceHandle, buf.pHeader, Win32.WaveHeader.SizeOfWaveHeader); } else { Win32.waveInUnprepareHeader(deviceHandle, buf.pHeader, Win32.WaveHeader.SizeOfWaveHeader); buf.Dispose(); Interlocked.Decrement(ref enqueuedBufferCount); } }; int mmret = Win32.waveInOpen(out deviceHandle, (uint)deviceId, ref wfx, new IntPtr(eventHandler.Win32ThreadID), IntPtr.Zero, Win32.CALLBACK_THREAD); if (mmret != Win32.MMSYSERR_NOERROR) { eventHandler.Dispose(); throw new Exception("Error on waveInOpen. (ret=" + mmret + ")"); } }