public SoundPlayer(Control owner, PullAudio pullAudio, short channels) { _channels = channels; _pullAudio = pullAudio; _soundDevice = new Device(); _soundDevice.SetCooperativeLevel(owner, CooperativeLevel.Priority); // Set up our wave format to 44,100Hz, with 16 bit resolution var wf = new WaveFormat { FormatTag = WaveFormatTag.Pcm, SamplesPerSecond = 44100, BitsPerSample = 16, Channels = channels }; wf.BlockAlign = (short)(wf.Channels * wf.BitsPerSample / 8); wf.AverageBytesPerSecond = wf.SamplesPerSecond * wf.BlockAlign; _samplesPerUpdate = 512; // Create a buffer with 2 seconds of sample data var bufferDesc = new BufferDescription(wf) { BufferBytes = _samplesPerUpdate * wf.BlockAlign * 2, ControlPositionNotify = true, GlobalFocus = true }; _soundBuffer = new SecondaryBuffer(bufferDesc, _soundDevice); var notify = new Notify(_soundBuffer); _fillEvent[0] = new AutoResetEvent(false); _fillEvent[1] = new AutoResetEvent(false); // Set up two notification events, one at halfway, and one at the end of the buffer var posNotify = new BufferPositionNotify[2]; posNotify[0] = new BufferPositionNotify { Offset = bufferDesc.BufferBytes / 2 - 1, EventNotifyHandle = _fillEvent[0].SafeWaitHandle.DangerousGetHandle() }; posNotify[1] = new BufferPositionNotify { Offset = bufferDesc.BufferBytes - 1, EventNotifyHandle = _fillEvent[1].SafeWaitHandle.DangerousGetHandle() }; notify.SetNotificationPositions(posNotify); _thread = new Thread(SoundPlayback) { Priority = ThreadPriority.Highest }; Pause(); _running = true; _thread.Start(); }
protected void SetBufferEvents() { // Goal: To Send While Recording // To Set The Buffer Size to get 200 milliseconds and divide it in half, // so that when the first half is filled the data can be used to send, // while the second half of the buffer is being filled with PCM Data try { autoResetEvent = new AutoResetEvent(false); // To wait for notifications notify = new Notify(captureBuffer); // The number of bytes that can trigger the notification event // the first half BufferPositionNotify bufferPositionNotify1 = new BufferPositionNotify(); // to describe the notification position bufferPositionNotify1.Offset = bufferSize / 2 - 1; // (= At the Half of The Buffer) to know where the notify event will trigger bufferPositionNotify1.EventNotifyHandle = autoResetEvent.SafeWaitHandle.DangerousGetHandle(); // Set The Event that will trigger after the offset reached // the last half BufferPositionNotify bufferPositionNotify2 = new BufferPositionNotify(); bufferPositionNotify2.Offset = bufferSize - 1; // (= At The Last Buffer) bufferPositionNotify2.EventNotifyHandle = autoResetEvent.SafeWaitHandle.DangerousGetHandle(); notify.SetNotificationPositions(new BufferPositionNotify[] { bufferPositionNotify1, bufferPositionNotify2 }); // The Tow Positions (First & Last) } catch { } }
private bool InitNotifications() { if (null == mRecBuffer) { MessageBox.Show("未创建录音缓冲区"); return(false); } // 创建一个通知事件,当缓冲队列满了就激发该事件. mNotificationEvent = new AutoResetEvent(false); // 创建一个线程管理缓冲区事件 if (null == mNotifyThread) { mNotifyThread = new Thread(new ThreadStart(WaitThread)); mNotifyThread.Start(); } // 设定通知的位置 BufferPositionNotify[] PositionNotify = new BufferPositionNotify[cNotifyNum + 1]; for (int i = 0; i < cNotifyNum; i++) { PositionNotify[i].Offset = (mNotifySize * i) + mNotifySize - 1; PositionNotify[i].EventNotifyHandle = mNotificationEvent.Handle; } mNotify = new Notify(mRecBuffer); mNotify.SetNotificationPositions(PositionNotify, cNotifyNum); return(true); }
private void CreateNotifyPositions() { checked { try { autoResetEvent = new AutoResetEvent(false); notify = new Notify(captureBuffer); BufferPositionNotify bufferPositionNotify = new BufferPositionNotify(); bufferPositionNotify.Offset = (int)Math.Round(unchecked ((double)bufferSize / 2.0 - 1.0)); bufferPositionNotify.EventNotifyHandle = autoResetEvent.SafeWaitHandle.DangerousGetHandle(); BufferPositionNotify bufferPositionNotify2 = new BufferPositionNotify(); bufferPositionNotify2.Offset = bufferSize - 1; bufferPositionNotify2.EventNotifyHandle = autoResetEvent.SafeWaitHandle.DangerousGetHandle(); notify.SetNotificationPositions(new BufferPositionNotify[2] { bufferPositionNotify, bufferPositionNotify2 }); } catch (Exception ex) { ProjectData.SetProjectError(ex); Exception ex2 = ex; ProjectData.ClearProjectError(); } } }
protected void SetBufferEvents() { // Отправлять данный во время записи // установить размер буфера 200 милисекунд и разделить его на два, // при заполнение первой части её мож использовать // вторая половина будет заполняться данными try { _eventToReset = new AutoResetEvent(false); // Ожидание уведомлений _not = new Notify(_captureBuffer); // Количество байтов, которые могут инициировать событие уведомления // первая часть BufferPositionNotify bufferPositionNotify1 = new BufferPositionNotify(); // Для описания позиции уведомления bufferPositionNotify1.Offset = _bufferSize / 2 - 1; // половине буфера, чтобы узнать, где будет происходить событие уведомления bufferPositionNotify1.EventNotifyHandle = _eventToReset.SafeWaitHandle.DangerousGetHandle(); // вторая часть BufferPositionNotify bufferPositionNotify2 = new BufferPositionNotify(); bufferPositionNotify2.Offset = _bufferSize - 1; bufferPositionNotify2.EventNotifyHandle = _eventToReset.SafeWaitHandle.DangerousGetHandle(); _not.SetNotificationPositions(new BufferPositionNotify[] { bufferPositionNotify1, bufferPositionNotify2 }); } catch { } }
private void Initialize() { int hresult = NativeMethods.DirectSoundCreate(IntPtr.Zero, out _device, IntPtr.Zero); if (hresult < 0) { Marshal.ThrowExceptionForHR(hresult); } _device.SetCooperativeLevel(_window, CooperativeLevel.Normal); GCHandleHelpers.Pin(new WaveFormat(_sampleRate, _sampleChannels, _sampleBits), waveFormat => { var description = new BufferDescription(BufferCapabilities.CtrlPositionNotify | BufferCapabilities.CtrlVolume, BlockCount * _sampleSize, waveFormat); _device.CreateSoundBuffer(description, out _buffer, IntPtr.Zero); }); ClearBuffer(); var positionEvents = new BufferPositionNotify[BlockCount] { new BufferPositionNotify(0 * _sampleSize, _position1Event), new BufferPositionNotify(1 * _sampleSize, _position2Event) }; ((IDirectSoundNotify)_buffer).SetNotificationPositions(positionEvents.Length, positionEvents); _buffer.Play(0, 0, BufferPlay.Looping); }
public StreamingSoundBuffer(Device device, WaveFormat format, ISoundDataProvider provider) { NextID++; this.device = device; this.provider = provider; BufferDescription description = new BufferDescription(format); description.BufferBytes = BufferSize; description.ControlPositionNotify = true; description.CanGetCurrentPosition = true; description.ControlVolume = true; description.LocateInHardware = false; description.LocateInSoftware = true; description.GlobalFocus = false; description.StickyFocus = false; try { buffer = new SecondaryBuffer(description, device); buffer.SetCurrentPosition(0); buffer.Volume = 0; } catch (Exception ex) { if (buffer != null) { buffer.Dispose(); } throw new SoundSystemException(ex, "Failed to create SecondaryBuffer ID {0}.", NextID); } notifier = new Notify(buffer); notifyEvent = new AutoResetEvent(false); BufferPositionNotify[] notifications = new BufferPositionNotify[Notifications]; for (int i = 0; i < Notifications; i++) { if (notifyEvent.SafeWaitHandle.IsClosed || notifyEvent.SafeWaitHandle.IsInvalid) { throw new SoundSystemException("SecondaryBuffer ID {0} notifier handle was closed or invalid.", NextID); } else { notifications[i].EventNotifyHandle = notifyEvent.SafeWaitHandle.DangerousGetHandle(); notifications[i].Offset = SectorSize * i - 1; } } notifier.SetNotificationPositions(notifications, Notifications); data = provider.GetNextChunk(); FillData(); FillData(); // do this twice, to have a 370 or so ms lead, in case something were to happen dataManager = new Thread(new ThreadStart(DataStream)); dataManager.Name = "Prometheus Sound Stream #" + NextID.ToString(); dataManager.Priority = ThreadPriority.AboveNormal; dataManager.Start(); // must lock buffer from now on }
public SoundPlayer(Control owner, PullAudio pullAudio, short channels) { this.channels = channels; this.pullAudio = pullAudio; this.soundDevice = new Device(); this.soundDevice.SetCooperativeLevel(owner, CooperativeLevel.Priority); // Set up our wave format to 44,100Hz, with 16 bit resolution WaveFormat wf = new WaveFormat(); wf.FormatTag = WaveFormatTag.Pcm; wf.SamplesPerSecond = 44100; wf.BitsPerSample = 16; wf.Channels = channels; wf.BlockAlign = (short)(wf.Channels * wf.BitsPerSample / 8); wf.AverageBytesPerSecond = wf.SamplesPerSecond * wf.BlockAlign; this.samplesPerUpdate = 512; // Create a buffer with 2 seconds of sample data BufferDescription bufferDesc = new BufferDescription(wf); bufferDesc.BufferBytes = this.samplesPerUpdate * wf.BlockAlign * 2; bufferDesc.ControlPositionNotify = true; bufferDesc.GlobalFocus = true; this.soundBuffer = new SecondaryBuffer(bufferDesc, this.soundDevice); Notify notify = new Notify(this.soundBuffer); fillEvent[0] = new AutoResetEvent(false); fillEvent[1] = new AutoResetEvent(false); // Set up two notification events, one at halfway, and one at the end of the buffer BufferPositionNotify[] posNotify = new BufferPositionNotify[2]; posNotify[0] = new BufferPositionNotify(); posNotify[0].Offset = bufferDesc.BufferBytes / 2 - 1; posNotify[0].EventNotifyHandle = fillEvent[0].Handle; posNotify[1] = new BufferPositionNotify(); posNotify[1].Offset = bufferDesc.BufferBytes - 1; posNotify[1].EventNotifyHandle = fillEvent[1].Handle; notify.SetNotificationPositions(posNotify); this.thread = new Thread(new ThreadStart(SoundPlayback)); this.thread.Priority = ThreadPriority.Highest; this.Pause(); this.running = true; this.thread.Start(); }
public DSoundPlayer(Control owner, PullAudio pullAudio, Qaryan.Audio.WaveFormat format) { this.pullAudio = pullAudio; this.soundDevice = new Device(); this.soundDevice.SetCooperativeLevel(owner, CooperativeLevel.Normal); // Set up our wave format to 44,100Hz, with 16 bit resolution DirectSound.WaveFormat wf = ConvertWaveFormat(format); // wf.FormatTag = DirectSound.WaveFormatTag.Pcm; // wf.SamplesPerSecond = 44100; // wf.BitsPerSample = 16; // wf.Channels = channels; // wf.BlockAlign = (short)(wf.Channels * wf.BitsPerSample / 8); // wf.AverageBytesPerSecond = wf.SamplesPerSecond * wf.BlockAlign; this.samplesPerUpdate = 1024; // Create a buffer with 5 seconds of sample data bufferDesc = new BufferDescription(wf); bufferDesc.BufferBytes = this.samplesPerUpdate * wf.BlockAlign * 5; bufferDesc.ControlPositionNotify = true; bufferDesc.GlobalFocus = true; this.soundBuffer = new SecondaryBuffer(bufferDesc, this.soundDevice); Notify notify = new Notify(this.soundBuffer); fillEvent[0] = new AutoResetEvent(false); fillEvent[1] = new AutoResetEvent(false); // Set up two notification events, one at halfway, and one at the end of the buffer BufferPositionNotify[] posNotify = new BufferPositionNotify[2]; posNotify[0] = new BufferPositionNotify(); posNotify[0].Offset = bufferDesc.BufferBytes / 2 - 1; posNotify[0].EventNotifyHandle = fillEvent[0].SafeWaitHandle.DangerousGetHandle(); posNotify[1] = new BufferPositionNotify(); posNotify[1].Offset = bufferDesc.BufferBytes - 1; posNotify[1].EventNotifyHandle = fillEvent[1].SafeWaitHandle.DangerousGetHandle(); notify.SetNotificationPositions(posNotify); this.thread = new Thread(new ThreadStart(SoundPlayback)); this.thread.SetApartmentState(ApartmentState.STA); this.thread.Name = "SoundPlayback"; this.thread.Priority = ThreadPriority.Highest; this.Pause(); this.running = true; this.thread.Start(); }
/// <summary> /// Initialize the SecondaryBuffer and Notify instances. /// </summary> protected void InitSecondaryBuffer() { if (SB != null) { SB.Dispose(); } if (Notify != null) { Notify.Dispose(); } BufferDescription description = new BufferDescription(WaveFormat); description.ControlPositionNotify = true; description.BufferBytes = (int)Math.Round(((double)WaveFormat.AverageBytesPerSecond * this.BufferLength.TotalSeconds)); description.ControlVolume = true; description.ControlEffects = false; description.Control3D = false; description.StickyFocus = true; SB = new SecondaryBuffer(description, Device); int length = SB.Caps.BufferBytes; byte[] bytes = new byte[length]; Random r = new Random(); r.NextBytes(bytes); Notify = new Notify(SB); BufferPositionNotify [] bpn = new BufferPositionNotify[3]; bpn[0] = new BufferPositionNotify(); bpn[0].Offset = length / 2 - 1; bpn[0].EventNotifyHandle = NotificationEvent.Handle; bpn[1] = new BufferPositionNotify(); bpn[1].Offset = length - 1; bpn[1].EventNotifyHandle = NotificationEvent.Handle; bpn[2] = new BufferPositionNotify(); bpn[2].Offset = (int)PositionNotifyFlag.OffsetStop; bpn[2].EventNotifyHandle = NotificationEvent.Handle; Notify.SetNotificationPositions(bpn, 3); if (Initialized != null) { Initialized(this, new EventArgs()); } }
//设置通知 private void CreateNotification() { BufferPositionNotify[] bpn = new BufferPositionNotify[iNotifyNum];//设置缓冲区通知个数 //设置通知事件 notifyevent = new AutoResetEvent(false); notifythread = new Thread(RecoData); notifythread.Start(); for (int i = 0; i < iNotifyNum; i++) { bpn[i].Offset = iNotifySize + i * iNotifySize - 1;//设置具体每个的位置 bpn[i].EventNotifyHandle = notifyevent.Handle; } myNotify = new Notify(capturebuffer); myNotify.SetNotificationPositions(bpn); }
public DirectSound(Control mainForm, int device, int samplesPerSecond, short bitsPerSample, short channels, int bufferSize, int bufferCount) { _fillQueue = new Queue(bufferCount); _playQueue = new Queue(bufferCount); for (int i = 0; i < bufferCount; i++) _fillQueue.Enqueue(new byte[bufferSize]); _bufferSize = bufferSize; _bufferCount = bufferCount; _zeroValue = bitsPerSample == 8 ? (byte)128 : (byte)0; _device = new Device(); _device.SetCooperativeLevel(mainForm, CooperativeLevel.Priority); WaveFormat wf = new WaveFormat(); wf.FormatTag = WaveFormatTag.Pcm; wf.SamplesPerSecond = samplesPerSecond; wf.BitsPerSample = bitsPerSample; wf.Channels = channels; wf.BlockAlign = (short)(wf.Channels * (wf.BitsPerSample / 8)); wf.AverageBytesPerSecond = (int)wf.SamplesPerSecond * (int)wf.BlockAlign; // Create a buffer BufferDescription bufferDesc = new BufferDescription(wf); bufferDesc.BufferBytes = _bufferSize * _bufferCount; bufferDesc.ControlPositionNotify = true; bufferDesc.GlobalFocus = true; _soundBuffer = new SecondaryBuffer(bufferDesc, _device); _notify = new Notify(_soundBuffer); BufferPositionNotify[] posNotify = new BufferPositionNotify[_bufferCount]; for (int i = 0; i < posNotify.Length; i++) { posNotify[i] = new BufferPositionNotify(); posNotify[i].Offset = i * _bufferSize; posNotify[i].EventNotifyHandle = _fillEvent.SafeWaitHandle.DangerousGetHandle(); } _notify.SetNotificationPositions(posNotify); _waveFillThread = new Thread(new ThreadStart(waveFillThreadProc)); _waveFillThread.IsBackground = true; _waveFillThread.Name = "Wave fill thread"; _waveFillThread.Priority = ThreadPriority.Highest; _waveFillThread.Start(); }
private void InitNotifications() { if (this.notify_ != null) { this.notify_.Dispose(); this.notify_ = null; } BufferPositionNotify[] array = new BufferPositionNotify[17]; for (int i = 0; i < 16; i++) { array[i].Offset = this.notifySize_ * i + this.notifySize_ - 1; array[i].EventNotifyHandle = this.notifyEvent_.SafeWaitHandle.DangerousGetHandle(); } this.notify_ = new Notify(this.captureBuffer_); this.notify_.SetNotificationPositions(array, 16); }
public void CreateNotification() { BufferPositionNotify[] bgn = new BufferPositionNotify[iNotifyNum]; notifyevent = new AutoResetEvent(false); notifythread = new Thread(RecoData); notifythread.IsBackground = true; notifythread.Start(); for (int i = 0; i < iNotifyNum; i++) { bgn[i].Offset = iNotifySize + i * iNotifySize - 1; bgn[i].EventNotifyHandle = notifyevent.Handle; } myNotify = new Notify(capturebuffer); myNotify.SetNotificationPositions(bgn); Console.WriteLine("Create notification successfully..."); }
private void SetSecondaryBuffer() { buffer = new SecondaryBuffer(bufferDesc, device); are = new AutoResetEvent(false); var notify = new Notify(buffer); var psa = new BufferPositionNotify[m_numberOfSectorsInBuffer]; for (int i = 0; i < m_numberOfSectorsInBuffer; i++) { psa[i].Offset = m_SectorSize * (i + 1) - 1; psa[i].EventNotifyHandle = are.SafeWaitHandle.DangerousGetHandle(); } notify.SetNotificationPositions(psa, m_numberOfSectorsInBuffer); }
private void UDP_CreateNotifyPositions() { try { autoResetEvent = new AutoResetEvent(false); notify = new Notify(captureBuffer); BufferPositionNotify bufferPositionNotify1 = new BufferPositionNotify(); bufferPositionNotify1.Offset = bufferSize / 2 - 1; bufferPositionNotify1.EventNotifyHandle = autoResetEvent.SafeWaitHandle.DangerousGetHandle(); BufferPositionNotify bufferPositionNotify2 = new BufferPositionNotify(); bufferPositionNotify2.Offset = bufferSize - 1; bufferPositionNotify2.EventNotifyHandle = autoResetEvent.SafeWaitHandle.DangerousGetHandle(); notify.SetNotificationPositions(new BufferPositionNotify[] { bufferPositionNotify1, bufferPositionNotify2 }); } catch (Exception ex) { MessageBox.Show(ex.Message, "VoiceChat-CreateNotifyPositions ()", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void InitNotifications() { if (notify_ != null) { notify_.Dispose(); notify_ = null; } BufferPositionNotify[] positionNotify = new BufferPositionNotify[NOTIFY_NUM + 1]; for (int i = 0; i < NOTIFY_NUM; i++) { positionNotify[i].Offset = (notifySize_ * i) + notifySize_ - 1; positionNotify[i].EventNotifyHandle = notifyEvent_.SafeWaitHandle.DangerousGetHandle(); } notify_ = new Notify(captureBuffer_); notify_.SetNotificationPositions(positionNotify, NOTIFY_NUM); }
/// <summary> /// Starts capture process. /// </summary> public void Start() { EnsureIdle(); isCapturing = true; WaveFormat format = new WaveFormat(); format.Channels = ChannelCount; format.BitsPerSample = BitsPerSample; format.SamplesPerSecond = SampleRate; format.FormatTag = WaveFormatTag.Pcm; format.BlockAlign = (short)((format.Channels * format.BitsPerSample + 7) / 8); format.AverageBytesPerSecond = format.BlockAlign * format.SamplesPerSecond; bufferLength = format.AverageBytesPerSecond * BufferSeconds; CaptureBufferDescription desciption = new CaptureBufferDescription(); desciption.Format = format; desciption.BufferBytes = bufferLength; capture = new Capture(device.Id); buffer = new CaptureBuffer(desciption, capture); int waitHandleCount = BufferSeconds * NotifyPointsInSecond; BufferPositionNotify[] positions = new BufferPositionNotify[waitHandleCount]; for (int i = 0; i < waitHandleCount; i++) { BufferPositionNotify position = new BufferPositionNotify(); position.Offset = (i + 1) * bufferLength / positions.Length - 1; position.EventNotifyHandle = positionEventHandle.DangerousGetHandle(); positions[i] = position; } notify = new Notify(buffer); notify.SetNotificationPositions(positions); terminated.Reset(); thread = new Thread(new ThreadStart(ThreadLoop)); thread.Name = "Sound capture"; thread.Start(); }
private void CreateNotifyPositions() { try { autoResetEvent = new AutoResetEvent(false); notify = new Notify(captureBuffer); BufferPositionNotify bufferPositionNotify1 = new BufferPositionNotify(); bufferPositionNotify1.Offset = bufferSize / 2 - 1; bufferPositionNotify1.EventNotifyHandle = autoResetEvent.SafeWaitHandle.DangerousGetHandle(); BufferPositionNotify bufferPositionNotify2 = new BufferPositionNotify(); bufferPositionNotify2.Offset = bufferSize - 1; bufferPositionNotify2.EventNotifyHandle = autoResetEvent.SafeWaitHandle.DangerousGetHandle(); notify.SetNotificationPositions(new BufferPositionNotify[] { bufferPositionNotify1, bufferPositionNotify2 }); } catch (Exception ex) { } }
public static void SetBufferEvents() { try { autoResetEvent = new AutoResetEvent(false); notify = new Notify(captureBuffer); BufferPositionNotify bufferPositionNotify1 = new BufferPositionNotify(); bufferPositionNotify1.Offset = bufferSize / 2 - 1; bufferPositionNotify1.EventNotifyHandle = autoResetEvent.SafeWaitHandle.DangerousGetHandle(); BufferPositionNotify bufferPositionNotify2 = new BufferPositionNotify(); bufferPositionNotify2.Offset = bufferSize - 1; bufferPositionNotify2.EventNotifyHandle = autoResetEvent.SafeWaitHandle.DangerousGetHandle(); notify.SetNotificationPositions(new BufferPositionNotify[] { bufferPositionNotify1, bufferPositionNotify2 }); } catch { } }
public DirectSound(Control mainForm, int device, int samplesPerSecond, short bitsPerSample, short channels, int bufferSize, int bufferCount) { this._fillQueue = new Queue(bufferCount); this._playQueue = new Queue(bufferCount); for (int i = 0; i < bufferCount; i++) { this._fillQueue.Enqueue(new byte[bufferSize]); } this._bufferSize = bufferSize; this._bufferCount = bufferCount; this._zeroValue = ((bitsPerSample == 8) ? 128 : 0); this._device = new Device(); this._device.SetCooperativeLevel(mainForm, CooperativeLevel.Priority); WaveFormat wfx = new WaveFormat(); wfx.FormatTag = WaveFormatTag.Pcm; wfx.SamplesPerSecond = samplesPerSecond; wfx.BitsPerSample = bitsPerSample; wfx.Channels = channels; wfx.BlockAlign = wfx.Channels * (wfx.BitsPerSample / 8); wfx.AverageBytesPerSecond = wfx.SamplesPerSecond * (int)wfx.BlockAlign; this._soundBuffer = new SecondaryBuffer(new BufferDescription(wfx) { BufferBytes = this._bufferSize * this._bufferCount, ControlPositionNotify = true, GlobalFocus = true }, this._device); this._notify = new Notify(this._soundBuffer); BufferPositionNotify[] array = new BufferPositionNotify[this._bufferCount]; for (int j = 0; j < array.Length; j++) { array[j] = new BufferPositionNotify(); array[j].Offset = j * this._bufferSize; array[j].EventNotifyHandle = this._fillEvent.SafeWaitHandle.DangerousGetHandle(); } this._notify.SetNotificationPositions(array); this._waveFillThread = new Thread(new ThreadStart(this.waveFillThreadProc)); this._waveFillThread.IsBackground = true; this._waveFillThread.Name = "Wave fill thread"; this._waveFillThread.Priority = ThreadPriority.Highest; this._waveFillThread.Start(); }
//Set up notifications private void CreateNotification() { BufferPositionNotify[] bpn = new BufferPositionNotify[iNotifyNum]; //Set the number of buffer notifications //Set the notification event notifyevent = new AutoResetEvent(false); notifythread = new Thread(RecoData); notifythread.IsBackground = true; notifythread.Start(); fftthread = new Thread(fftFunction); fftthread.IsBackground = true; fftthread.Start(); for (int i = 0; i < iNotifyNum; i++) { bpn[i].Offset = iNotifySize + i * iNotifySize - 1;//Set each specific location bpn[i].EventNotifyHandle = notifyevent.SafeWaitHandle.DangerousGetHandle(); } myNotify = new Notify(capturebuffer); myNotify.SetNotificationPositions(bpn); }
private void CreateNotifyPositions() { try { autoResetEvent = new AutoResetEvent(false); notify = new Notify(captureBuffer); BufferPositionNotify bufferPositionNotify1 = new BufferPositionNotify(); bufferPositionNotify1.Offset = bufferSize / 2 - 1; bufferPositionNotify1.EventNotifyHandle = autoResetEvent.SafeWaitHandle.DangerousGetHandle(); BufferPositionNotify bufferPositionNotify2 = new BufferPositionNotify(); bufferPositionNotify2.Offset = bufferSize - 1; bufferPositionNotify2.EventNotifyHandle = autoResetEvent.SafeWaitHandle.DangerousGetHandle(); notify.SetNotificationPositions(new BufferPositionNotify[] { bufferPositionNotify1, bufferPositionNotify2 }); } catch (Exception ex) { // MessageBox.Show(ex.Message, "VoiceChat-CreateNotifyPositions ()", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void CreateNotifyPositions() { try { autoResetEvent = new AutoResetEvent(false); notify = new Notify(captureBuffer); BufferPositionNotify bufferPositionNotify1 = new BufferPositionNotify(); bufferPositionNotify1.Offset = bufferSize / 2 - 1; bufferPositionNotify1.EventNotifyHandle = autoResetEvent.SafeWaitHandle.DangerousGetHandle(); BufferPositionNotify bufferPositionNotify2 = new BufferPositionNotify(); bufferPositionNotify2.Offset = bufferSize - 1; bufferPositionNotify2.EventNotifyHandle = autoResetEvent.SafeWaitHandle.DangerousGetHandle(); notify.SetNotificationPositions(new BufferPositionNotify[] { bufferPositionNotify1, bufferPositionNotify2 }); } catch (Exception) { //MessageBox.Show("Wystąpił problem podczas metody \"CreateNotifyPositions()\"!", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public DirectSoundOut(Control owner, AudioPCMConfig pcm, int delay) { this.m_settings = new AudioEncoderSettings(pcm); //buffer = new CyclicBuffer(44100*4/10); //output = new CycilcBufferOutputStream(buffer); //input = new CycilcBufferInputStream(buffer); dSound = new Device(); dSound.SetCooperativeLevel(owner, CooperativeLevel.Priority); format.AverageBytesPerSecond = pcm.SampleRate * pcm.BlockAlign; format.BitsPerSample = (short)pcm.BitsPerSample; format.BlockAlign = (short)pcm.BlockAlign; format.Channels = (short)pcm.ChannelCount; format.SamplesPerSecond = pcm.SampleRate; format.FormatTag = WaveFormatTag.Pcm; SecBufByteSize = delay * pcm.SampleRate * pcm.BlockAlign / 1000; description.Format = format; description.BufferBytes = SecBufByteSize; description.CanGetCurrentPosition = true; description.ControlPositionNotify = true; //description.ControlVolume = true; description.GlobalFocus = true; secondaryBuffer = new SecondaryBuffer(description, dSound); //secondaryBuffer.Volume = 100; notify = new Notify(secondaryBuffer); BufferPositionNotify[] bufferPositions = new BufferPositionNotify[3]; bufferPositions[0].Offset = 0; bufferPositions[0].EventNotifyHandle = SecBufNotifyAtBegin.Handle; bufferPositions[1].Offset = SecBufByteSize / 3; bufferPositions[1].EventNotifyHandle = SecBufNotifyAtOneThird.Handle; bufferPositions[2].Offset = 2 * SecBufByteSize / 3; bufferPositions[2].EventNotifyHandle = SecBufNotifyAtTwoThirds.Handle; notify.SetNotificationPositions(bufferPositions); pcmStream = new MemoryStream(SecBufByteSize); SecBufWaitHandles = new WaitHandle[] { SecBufNotifyAtBegin, SecBufNotifyAtOneThird, SecBufNotifyAtTwoThirds }; //wavoutput = new WAVWriter("", output, pcm); }
private void CreateNotifyPositions() { try { autoResetEvent = new AutoResetEvent(false); notify = new Notify(captureBuffer); BufferPositionNotify bufferPositionNotify1 = new BufferPositionNotify { Offset = buffersize / 2 - 1, EventNotifyHandle = autoResetEvent.SafeWaitHandle.DangerousGetHandle() }; BufferPositionNotify bufferPositionNotify2 = new BufferPositionNotify { Offset = buffersize - 1, EventNotifyHandle = autoResetEvent.SafeWaitHandle.DangerousGetHandle() }; notify.SetNotificationPositions(new BufferPositionNotify[] { bufferPositionNotify1, bufferPositionNotify2 }); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error on CreatePositionNotify", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private bool InitNotifications() { if ((CaptureBuffer)null == this.mRecBuffer) { return(false); } this.mNotificationEvent = new AutoResetEvent(false); if (this.mNotifyThread == null) { this.mNotifyThread = new Thread(new ThreadStart(this.WaitThread)); this.mNotifyThread.Start(); } BufferPositionNotify[] notify = new BufferPositionNotify[17]; for (int index = 0; index < 16; ++index) { notify[index].Offset = this.mNotifySize * index + this.mNotifySize - 1; notify[index].EventNotifyHandle = this.mNotificationEvent.SafeWaitHandle.DangerousGetHandle(); } this.mNotify = new Notify(this.mRecBuffer); this.mNotify.SetNotificationPositions(notify, 16); return(true); }
private void startRecordingOrMonitoring(AudioLibPCMFormat pcmFormat, bool recordingToFile) { RecordingPCMFormat = pcmFormat; #if USE_SHARPDX WaveFormat waveFormat = new WaveFormat((int)RecordingPCMFormat.SampleRate, 16, (int)RecordingPCMFormat.NumberOfChannels); #else WaveFormat waveFormat = new WaveFormat(); waveFormat.FormatTag = WaveFormatTag.Pcm; waveFormat.Channels = (short)RecordingPCMFormat.NumberOfChannels; waveFormat.SamplesPerSecond = (int)RecordingPCMFormat.SampleRate; waveFormat.BitsPerSample = (short)RecordingPCMFormat.BitDepth; waveFormat.AverageBytesPerSecond = (int)RecordingPCMFormat.SampleRate * RecordingPCMFormat.BlockAlign; waveFormat.BlockAlign = (short)RecordingPCMFormat.BlockAlign; #endif uint byteRate = RecordingPCMFormat.SampleRate * RecordingPCMFormat.BlockAlign; int pcmDataBufferSize = (int)(byteRate * REFRESH_INTERVAL_MS / 1000.0); pcmDataBufferSize -= pcmDataBufferSize % RecordingPCMFormat.BlockAlign; // here we are probably wasting some heap memory, // because the event arg payload buffer (for "data available" event) // contains the delta between capture and read circular buffer positions. // however, this makes the memory re-alloc (i.e. buffer resize) routine simpler, // that is to say here only when start record/monitor, // instead of inside the DirectAudio capture thread (based on the actual circular buffer delta). m_PcmDataBufferLength = pcmDataBufferSize * NOTIFICATIONS; if (m_PcmDataBuffer == null) { Console.WriteLine("ALLOCATING m_PcmDataBuffer"); m_PcmDataBuffer = new byte[m_PcmDataBufferLength]; } else if (m_PcmDataBuffer.Length < m_PcmDataBufferLength) { Console.WriteLine("m_PcmDataBuffer.resize"); Array.Resize(ref m_PcmDataBuffer, m_PcmDataBufferLength); } int circularBufferSize = pcmDataBufferSize * NOTIFICATIONS; CaptureBufferDescription bufferDescription = new CaptureBufferDescription(); bufferDescription.BufferBytes = circularBufferSize; bufferDescription.Format = waveFormat; #if USE_SHARPDX bufferDescription.Flags = CaptureBufferCapabilitiesFlags.WaveMapped; //CaptureBufferCapabilitiesFlags.ControlEffects if (InputDevice == null) { Console.WriteLine("/// InputDevice NULL, attempting reset..."); List <InputDevice> inputDevices = InputDevices; Console.WriteLine("/// InputDevices: " + inputDevices.Count); SetInputDevice("dummy"); } m_CircularBuffer = new CaptureBuffer(InputDevice.Capture, bufferDescription); #else m_CircularBuffer = new CaptureBuffer(bufferDescription, InputDevice.Capture); #endif #if FORCE_SINGLE_NOTIFICATION_EVENT m_CircularBufferNotificationEvent = new AutoResetEvent(false); #else m_CircularBufferNotificationEvents = new AutoResetEvent[NOTIFICATIONS]; #endif #if USE_SHARPDX NotificationPosition[] m_BufferPositionNotify = new NotificationPosition[NOTIFICATIONS]; #else BufferPositionNotify[] m_BufferPositionNotify = new BufferPositionNotify[NOTIFICATIONS]; #endif for (int i = 0; i < NOTIFICATIONS; i++) { #if USE_SHARPDX m_BufferPositionNotify[i] = new NotificationPosition(); #endif m_BufferPositionNotify[i].Offset = (pcmDataBufferSize * i) + pcmDataBufferSize - 1; #if FORCE_SINGLE_NOTIFICATION_EVENT #if USE_SHARPDX m_BufferPositionNotify[i].WaitHandle = m_CircularBufferNotificationEvent; //m_BufferPositionNotify[i].EventNotifyHandlePointer = m_CircularBufferNotificationEvent.SafeWaitHandle.DangerousGetHandle(); #else m_BufferPositionNotify[i].EventNotifyHandle = m_CircularBufferNotificationEvent.SafeWaitHandle.DangerousGetHandle(); #endif #else m_CircularBufferNotificationEvents[i] = new AutoResetEvent(false); #if USE_SHARPDX m_BufferPositionNotify[i].WaitHandle = m_CircularBufferNotificationEvents[i]; //m_BufferPositionNotify[i].EventNotifyHandlePointer = m_CircularBufferNotificationEvents[i].SafeWaitHandle.DangerousGetHandle(); #else m_BufferPositionNotify[i].EventNotifyHandle = m_CircularBufferNotificationEvents[i].SafeWaitHandle.DangerousGetHandle(); #endif #endif } #if USE_SHARPDX m_CircularBuffer.SetNotificationPositions(m_BufferPositionNotify); #else m_Notify = new Notify(m_CircularBuffer); m_Notify.SetNotificationPositions(m_BufferPositionNotify, NOTIFICATIONS); #endif m_CircularBufferReadPositon = 0; m_RecordingFileWriter = null; m_TotalRecordedBytes = 0; #if FORCE_SINGLE_NOTIFICATION_EVENT m_PreviousTotalRecordedBytes = 0; #endif if (recordingToFile) { int i = -1; do { i++; m_RecordedFilePath = RecordingDirectory + Path.DirectorySeparatorChar + i.ToString() + WavFormatConverter.AUDIO_WAV_EXTENSION; } while (File.Exists(m_RecordedFilePath)); Stream stream = File.Create(m_RecordedFilePath); try { m_RecordedFileRiffHeaderSize = RecordingPCMFormat.RiffHeaderWrite(stream, 0); } finally { stream.Close(); } } ThreadStart threadDelegate = delegate() { try { circularBufferRefreshThreadMethod(); } catch (ThreadAbortException ex) { // } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); } finally { lock (LOCK_THREAD_INSTANCE) { m_CircularBufferRefreshThread = null; } } //lock (LOCK_THREAD_INSTANCE) //{ // m_CircularBufferRefreshThread = null; //} }; lock (LOCK_THREAD_INSTANCE) { m_CircularBufferRefreshThread = new Thread(threadDelegate); m_CircularBufferRefreshThread.Name = "Recorder Notify Thread"; m_CircularBufferRefreshThread.Priority = ThreadPriority.AboveNormal; m_CircularBufferRefreshThread.IsBackground = true; CurrentState = (recordingToFile ? State.Recording : State.Monitoring); m_CircularBuffer.Start(true); m_CircularBufferRefreshThread.Start(); #if FORCE_SINGLE_NOTIFICATION_EVENT m_CircularBufferTimer.Start(); #endif } //Console.WriteLine("Recorder notify thread start."); }
private void PlayFile(FileInfo FI) { lock (this) { if (this.AudioDevice == null) { this.AudioDevice = new Device(); AudioDevice.SetCooperativeLevel(this, CooperativeLevel.Normal); } this.StopPlayback(); WaveFormat fmt = new WaveFormat(); fmt.FormatTag = WaveFormatTag.Pcm; fmt.Channels = FI.AudioFile.Channels; fmt.SamplesPerSecond = FI.AudioFile.SampleRate; fmt.BitsPerSample = 16; fmt.BlockAlign = (short)(FI.AudioFile.Channels * (fmt.BitsPerSample / 8)); fmt.AverageBytesPerSecond = fmt.SamplesPerSecond * fmt.BlockAlign; BufferDescription BD = new BufferDescription(fmt); BD.BufferBytes = this.AudioBufferSize; BD.GlobalFocus = true; BD.StickyFocus = true; if (this.chkBufferedPlayback.Checked) { BD.ControlPositionNotify = true; this.CurrentBuffer = new SecondaryBuffer(BD, this.AudioDevice); if (this.AudioUpdateTrigger == null) { this.AudioUpdateTrigger = new AutoResetEvent(false); } int ChunkSize = this.AudioBufferSize / this.AudioBufferMarkers; BufferPositionNotify[] UpdatePositions = new BufferPositionNotify[this.AudioBufferMarkers]; for (int i = 0; i < this.AudioBufferMarkers; ++i) { UpdatePositions[i] = new BufferPositionNotify(); UpdatePositions[i].EventNotifyHandle = this.AudioUpdateTrigger.SafeWaitHandle.DangerousGetHandle(); UpdatePositions[i].Offset = ChunkSize * i; } Notify N = new Notify(this.CurrentBuffer); N.SetNotificationPositions(UpdatePositions); this.CurrentStream = FI.AudioFile.OpenStream(); this.CurrentBuffer.Write(0, this.CurrentStream, this.CurrentBuffer.Caps.BufferBytes, LockFlag.EntireBuffer); if (this.CurrentStream.Position < this.CurrentStream.Length) { this.AudioUpdateTrigger.Reset(); this.AudioUpdateThread = new Thread(new ThreadStart(this.AudioUpdate)); this.AudioUpdateThread.Start(); this.btnPause.Enabled = true; this.btnStop.Enabled = true; this.AudioIsLooping = true; } else { this.CurrentStream.Close(); this.CurrentStream = null; this.AudioIsLooping = false; } } else { this.CurrentStream = FI.AudioFile.OpenStream(true); this.CurrentBuffer = new SecondaryBuffer(this.CurrentStream, BD, this.AudioDevice); this.btnPause.Enabled = true; this.btnStop.Enabled = true; } this.CurrentBuffer.Play(0, (this.AudioIsLooping ? BufferPlayFlags.Looping : BufferPlayFlags.Default)); } }
/// <summary> /// 创建播放服务对象 /// </summary> /// <param name="owner">宿主</param> /// <param name="deviceIndex">设备序号(0 - 默认设备)</param> /// <param name="channelCount">通道数</param> /// <param name="frequency">采样频率(次/秒)</param> /// <param name="sampleSize">样本尺寸(位/次)</param> /// <param name="bufferSectionTimeSpan">缓冲区片段的时间间隔</param> /// <param name="bufferSectionCount">缓冲区片段数</param> /// <param name="notificationEvent">通知点信号(工作线程等待此信号)</param> public SoundPlayer(Control owner, int deviceIndex, short channelCount, int frequency, short sampleSize, TimeSpan bufferSectionTimeSpan, int bufferSectionCount, AutoResetEvent notificationEvent) : base() { //宿主 this.Owner = owner; #region 源 this.Source = new MemoryStream(); #endregion #region 设备 DevicesCollection devices = new DevicesCollection(); this.Device = new Device(devices[deviceIndex].DriverGuid); //协作等级 this.Device.SetCooperativeLevel(this.Owner, CooperativeLevel.Priority); #endregion #region 缓冲区 #region Wave格式 WaveFormat format = new WaveFormat(); format.FormatTag = WaveFormatTag.Pcm; //格式类型 format.Channels = channelCount; //通道数 format.SamplesPerSecond = frequency; //采样频率(次/秒) format.BitsPerSample = sampleSize; //样本尺寸(位/次) format.BlockAlign = (short)((format.BitsPerSample / 8) * format.Channels); //数据块的最小单元(字节/次) format.AverageBytesPerSecond = format.BlockAlign * format.SamplesPerSecond; //采样性能(字节/秒) #endregion //缓冲区片段尺寸 this.BufferSectionSize = format.AverageBytesPerSecond * (int)bufferSectionTimeSpan.TotalSeconds; //缓冲区尺寸 this.BufferSize = this.BufferSectionSize * bufferSectionCount; //缓冲区描述 BufferDescription bufferDescription = new BufferDescription(format); bufferDescription.BufferBytes = this.BufferSize; bufferDescription.ControlPositionNotify = true; bufferDescription.CanGetCurrentPosition = true; bufferDescription.GlobalFocus = true; //允许后台播放 //创建 this.Buffer = new SecondaryBuffer(bufferDescription, this.Device); #endregion #region 缓冲区位置通知序列 //通知点信号 this.NotificationEvent = notificationEvent; //位置通知序列 BufferPositionNotify[] bufferPositionNotifys = new BufferPositionNotify[bufferSectionCount]; for (int i = 0; i < bufferSectionCount; i++) { bufferPositionNotifys[i].Offset = this.BufferSectionSize * i; //通知点 bufferPositionNotifys[i].EventNotifyHandle = this.NotificationEvent.SafeWaitHandle.DangerousGetHandle(); //通知点信号 Set() } //将位置通知序列指派到缓冲区 (new Notify(this.Buffer)).SetNotificationPositions(bufferPositionNotifys); #endregion #region 工作线程 this.ThreadWorking = true; this.WorkingThread = new Thread(new ParameterizedThreadStart(this.WorkingThreadProcess)); this.WorkingThread.IsBackground = true; this.WorkingThread.Start(this.NotificationEvent); //带入参数 #endregion //启动 this.Idle = true; this.LastWritePosition = -1; //初始化为负数,播放时再次初始化 this.Buffer.Play(0, BufferPlayFlags.Looping); }
/// <summary> /// 创建通知 /// </summary> private void CreateNotification() { BufferPositionNotify[] bpn = new BufferPositionNotify[m_nNotifyNum];//设置缓冲区通知个数 //设置通知事件 m_areNeedNewData = new AutoResetEvent(false); m_trdNodify = new Thread(PlayData); m_trdNodify.IsBackground = true; m_trdNodify.Start(); for (int i = 0; i < m_nNotifyNum; i++) { bpn[i].Offset = m_nNotifySize + i * m_nNotifySize - 1;//设置具体每个的位置 bpn[i].EventNotifyHandle = m_areNeedNewData.SafeWaitHandle.DangerousGetHandle(); } m_ntfNeedNewData = new Notify(m_secBuf); m_ntfNeedNewData.SetNotificationPositions(bpn); }
public DirectSound( Form form, int sampleRate, int bufferCount) { if ((sampleRate % 50) != 0) { throw new ArgumentOutOfRangeException("sampleRate", "Sample rate must be a multiple of 50!"); } _sampleRate = sampleRate; var bufferSize = sampleRate / 50; for (int i = 0; i < bufferCount; i++) { _fillQueue.Enqueue(new uint[bufferSize]); } _bufferSize = bufferSize; _bufferCount = bufferCount; _zeroValue = 0; _device = new Device(); _device.SetCooperativeLevel(form, CooperativeLevel.Priority); // we always use 16 bit stereo (uint per sample) const short channels = 2; const short bitsPerSample = 16; const int sampleSize = 4; // channels * (bitsPerSample / 8); var wf = new WaveFormat(); wf.FormatTag = WaveFormatTag.Pcm; wf.SamplesPerSecond = _sampleRate; wf.BitsPerSample = bitsPerSample; wf.Channels = channels; wf.BlockAlign = (short)(wf.Channels * (wf.BitsPerSample / 8)); wf.AverageBytesPerSecond = wf.SamplesPerSecond * wf.BlockAlign; // Create a buffer using (var bufferDesc = new BufferDescription(wf)) { bufferDesc.BufferBytes = _bufferSize * sampleSize * _bufferCount; bufferDesc.ControlPositionNotify = true; bufferDesc.GlobalFocus = true; _soundBuffer = new SecondaryBuffer(bufferDesc, _device); } _notify = new Notify(_soundBuffer); var posNotify = new BufferPositionNotify[_bufferCount]; for (int i = 0; i < posNotify.Length; i++) { posNotify[i] = new BufferPositionNotify(); posNotify[i].Offset = i * _bufferSize * sampleSize; posNotify[i].EventNotifyHandle = _fillEvent.SafeWaitHandle.DangerousGetHandle(); } _notify.SetNotificationPositions(posNotify); _wavePlayThread = new Thread(WavePlayThreadProc); _wavePlayThread.IsBackground = true; _wavePlayThread.Name = "WavePlay"; _wavePlayThread.Priority = ThreadPriority.Highest; _wavePlayThread.Start(); }
public void CreateNotification() { BufferPositionNotify[] bpn = new BufferPositionNotify[iNotifyNum]; // 設置缓衝區通知個數 // 設置通知事件 notifyevent = new AutoResetEvent(false); notifythread = new Thread(new ThreadStart(RecodeData)); // 通知觸發事件 notifythread.Start(); for (int i = 0; i < iNotifyNum; i++) { bpn[i].Offset = iNotifySize + i * iNotifySize - 1; // 設置具體每個的位置 bpn[i].EventNotifyHandle = notifyevent.SafeWaitHandle.DangerousGetHandle(); } myNotify = new Notify(capturebuffer); myNotify.SetNotificationPositions(bpn); }
protected void SetBufferEvents() { try { autoResetEvent = new AutoResetEvent(false); notify = new Notify(captureBuffer); BufferPositionNotify bufferPositionNotify1 = new BufferPositionNotify(); bufferPositionNotify1.Offset = bufferSize / 2 - 1; bufferPositionNotify1.EventNotifyHandle = autoResetEvent.SafeWaitHandle.DangerousGetHandle(); BufferPositionNotify bufferPositionNotify2 = new BufferPositionNotify(); bufferPositionNotify2.Offset = bufferSize - 1; // bufferPositionNotify2.EventNotifyHandle = autoResetEvent.SafeWaitHandle.DangerousGetHandle(); notify.SetNotificationPositions(new BufferPositionNotify[] { bufferPositionNotify1, bufferPositionNotify2 }); // The Tow Positions (First & Last) } catch (Exception) { } }
public PlayerClass(AudioBookConverterMain Caller, string filename) { if (GetSourceExt(filename) != "mp3") { return; } file = filename; Parent = Caller; Microsoft.DirectX.DirectSound.WaveFormat format = new Microsoft.DirectX.DirectSound.WaveFormat(); WmaStream wmastr = new WmaStream(filename); format.BlockAlign = wmastr.Format.nBlockAlign; format.Channels = wmastr.Format.nChannels; format.SamplesPerSecond = wmastr.Format.nSamplesPerSec; format.BitsPerSample = wmastr.Format.wBitsPerSample; format.AverageBytesPerSecond = format.BlockAlign * format.SamplesPerSecond; wmastr.Dispose(); BufferDescription desc = new BufferDescription(format); desc.ControlPan = true; desc.GlobalFocus = true; desc.BufferBytes = 262144; desc.ControlPositionNotify = true; desc.CanGetCurrentPosition = true; desc.ControlVolume = true; desc.StickyFocus = true; desc.LocateInSoftware = true; desc.ControlEffects = false; desc.LocateInHardware = false; desc.Control3D = false; //MemoryStream bufferstream = new MemoryStream(262144); Device device = new Device(); device.SetCooperativeLevel(Parent, CooperativeLevel.Priority); sound = new SecondaryBuffer(desc, device); sound.SetCurrentPosition(1); sound.Volume = 0; sound.Pan = 0; BufferNotificationEvent = new AutoResetEvent(false); BufferNotify = new Notify(sound); BufferPositionNotify[] BufferPositions = new BufferPositionNotify[2]; BufferPositions[0].Offset = 0; BufferPositions[0].EventNotifyHandle = BufferNotificationEvent.Handle; BufferPositions[1].Offset = (desc.BufferBytes / 2); BufferPositions[1].EventNotifyHandle = BufferNotificationEvent.Handle; BufferNotify.SetNotificationPositions(BufferPositions); DataTransferThread = new Thread(new ThreadStart(WMDataFill)); //if (GetSourceExt(filename) =="mp4") DataTransferThread = new Thread(new ThreadStart(FaadDataFill)); //if (GetSourceExt(filename) =="flac") DataTransferThread = new Thread(new ThreadStart(FlacDataFill)); //if (GetSourceExt(filename) =="ogg") DataTransferThread = new Thread(new ThreadStart(OggDataFill)); DataTransferThread.Name = "BufferFill"; DataTransferThread.Priority = ThreadPriority.Highest; DataTransferThread.Start(); }
public void SetNotificationPositions(BufferPositionNotify[] Positions) { Array RealPositions = Array.CreateInstance(BufferPositionNotify.TMe, Positions.Length); for (int i = 0; i < Positions.Length; ++i) { RealPositions.SetValue(Positions[i].Me, i); } TMe.InvokeMember("SetNotificationPositions", BindingFlags.InvokeMethod, null, Me, new object[] { RealPositions }, Application.CurrentCulture); }
private bool InitNotifications() { if (null == mRecBuffer) { Debug.WriteLine("Capture Buffer is null."); return false; } // 创建一个通知事件,当缓冲队列满了就激发该事件. mNotificationEvent = new AutoResetEvent(false); // 创建一个线程管理缓冲区事件 if (null == mNotifyThread) { mNotifyThread = new Thread(new ThreadStart(WaitThread)); mNotifyThread.Start(); } // 设定通知的位置 BufferPositionNotify[] PositionNotify = new BufferPositionNotify[cNotifyNum]; for (int i = 0; i < cNotifyNum; i++) { PositionNotify[i].Offset = (mNotifySize * i) + mNotifySize - 1; PositionNotify[i].EventNotifyHandle = mNotificationEvent.Handle; } mNotify = new Notify(mRecBuffer); mNotify.SetNotificationPositions(PositionNotify); return true; }
private static void PlayThread(object osn) { EmulatorForm myform = (EmulatorForm)osn; SecondaryBuffer SecBuf; AutoResetEvent SecBufNotifyAtHalf = new AutoResetEvent(false); AutoResetEvent SecBufNotifyAtBeginning = new AutoResetEvent(false); int SamplingRate = (int)myform._samplingRate; int HoldThisManySamples = (int)(1 * SamplingRate); int BlockAlign = 2; int SecBufByteSize = HoldThisManySamples * BlockAlign; WaveFormat MyWaveFormat = new WaveFormat(); // Set the format MyWaveFormat.AverageBytesPerSecond = (int)(myform._samplingRate * BlockAlign); MyWaveFormat.BitsPerSample = (short)16; MyWaveFormat.BlockAlign = (short)BlockAlign; MyWaveFormat.Channels = (short)1; MyWaveFormat.SamplesPerSecond = (int)myform._samplingRate; MyWaveFormat.FormatTag = WaveFormatTag.Pcm; BufferDescription MyDescription; // Set BufferDescription MyDescription = new BufferDescription(); MyDescription.Format = MyWaveFormat; MyDescription.BufferBytes = HoldThisManySamples * BlockAlign; MyDescription.CanGetCurrentPosition = true; MyDescription.ControlPositionNotify = true; MyDescription.GlobalFocus = true; // Create the buffer SecBuf = new SecondaryBuffer(MyDescription,myform._directSoundDevice); Notify MyNotify; MyNotify = new Notify(SecBuf); BufferPositionNotify[] MyBufferPositions = new BufferPositionNotify[2]; MyBufferPositions[0].Offset = 0; MyBufferPositions[0].EventNotifyHandle = SecBufNotifyAtBeginning.Handle; MyBufferPositions[1].Offset = (HoldThisManySamples / 2) * BlockAlign; MyBufferPositions[1].EventNotifyHandle = SecBufNotifyAtHalf.Handle; MyNotify.SetNotificationPositions(MyBufferPositions); WaitHandle[] SecBufWaitHandles = { SecBufNotifyAtBeginning, SecBufNotifyAtHalf }; Int16[] buffer; buffer = myform._sn.GenerateSamples((uint)HoldThisManySamples, ""); SecBuf.Write(0, buffer, LockFlag.None); SecBuf.Play(0, BufferPlayFlags.Looping); int SecBufNextWritePosition = 0; while (myform._bufferPlaying) { int WriteCount = 0, PlayPosition = SecBuf.PlayPosition, WritePosition = SecBuf.WritePosition; if (SecBufNextWritePosition < PlayPosition && (WritePosition >= PlayPosition || WritePosition < SecBufNextWritePosition)) WriteCount = PlayPosition - SecBufNextWritePosition; else if (SecBufNextWritePosition > WritePosition && WritePosition >= PlayPosition) WriteCount = (SecBufByteSize - SecBufNextWritePosition) + PlayPosition; // System.Diagnostics.Debug.WriteLine("WC: "+WriteCount.ToString()); if (WriteCount > 0) { WriteCount = (int)Math.Min(WriteCount,1000); buffer = myform._sn.GenerateSamples((uint)WriteCount/2, ""); SecBuf.Write( SecBufNextWritePosition, buffer, LockFlag.None); SecBufNextWritePosition = (SecBufNextWritePosition + WriteCount) % SecBufByteSize; } else { WaitHandle.WaitAny(SecBufWaitHandles, new TimeSpan(0, 0, 5), true); } } SecBuf.Dispose(); MyDescription.Dispose(); MyNotify.Dispose(); }
/// <summary> /// Initialize the SecondaryBuffer and Notify instances. /// </summary> protected void InitSecondaryBuffer() { if (SB != null) SB.Dispose(); if (Notify != null) Notify.Dispose(); BufferDescription description = new BufferDescription(WaveFormat); description.ControlPositionNotify = true; description.BufferBytes = (int)Math.Round(((double)WaveFormat.AverageBytesPerSecond * this.BufferLength.TotalSeconds)); description.ControlVolume = true; description.ControlEffects = false; description.Control3D = false; description.StickyFocus = true; SB = new SecondaryBuffer(description, Device); int length = SB.Caps.BufferBytes; byte[] bytes = new byte[length]; Random r = new Random(); r.NextBytes(bytes); Notify = new Notify(SB); BufferPositionNotify []bpn = new BufferPositionNotify[3]; bpn[0] = new BufferPositionNotify(); bpn[0].Offset = length/2-1; bpn[0].EventNotifyHandle = NotificationEvent.Handle; bpn[1] = new BufferPositionNotify(); bpn[1].Offset = length-1; bpn[1].EventNotifyHandle = NotificationEvent.Handle; bpn[2] = new BufferPositionNotify(); bpn[2].Offset = (int)PositionNotifyFlag.OffsetStop; bpn[2].EventNotifyHandle = NotificationEvent.Handle; Notify.SetNotificationPositions(bpn, 3); if (Initialized != null) Initialized(this, new EventArgs()); }