public bool Play() { try { lock (_syncObj) { if (_secondaryBuffer == null) { return(false); } // Set the position at the beginning of the sound buffer. _secondaryBuffer.CurrentPosition = 0; // Set volume of the buffer to 100% _secondaryBuffer.Volume = 0; // Play the contents of the secondary sound buffer. _secondaryBuffer.Play(0, PlayFlags.Looping); _isPlaying = true; } } catch (Exception ex) { ServiceRegistration.Get <ILogger>().Warn("LibRetroDirectSound: Failed to start playback", ex); return(false); } return(true); }
public static void PlaySound3d(SecondarySoundBuffer Sound, bool bCloseFirst, bool bLoopSound, double x, double y, double z) { lock (playLock) { SoundBuffer3D DS3DBuffer = new SoundBuffer3D(Sound); //stop currently playing waves? if (bCloseFirst) { Sound.Stop(); Sound.CurrentPosition = 0; } //set the position DS3DBuffer.Position = Get3DVector(x, y, z); //loop the sound? if (bLoopSound) { Sound.Play(0, SharpDX.DirectSound.PlayFlags.Looping); } else { Sound.Play(0, SharpDX.DirectSound.PlayFlags.None); } DS3DBuffer.Dispose(); } //lock }
private void SetEndNotification(int indexInBuffer) { EndNotificationPosition[0].Offset = indexInBuffer; // do this quickly to avoid possible sound glitch buffer.Stop(); buffer.SetNotificationPositions(EndNotificationPosition); buffer.Play(0, PlayFlags.Looping); }
public bool Play() { if (_buffer != null) { _playFlag = PlayFlags.None; _buffer.Play(0, _playFlag); return(true); } return(false); }
public void Play(bool _looping) { if (_looping) { secondarySoundBuffer.Play(0, PlayFlags.Looping); } else { secondarySoundBuffer.Play(0, PlayFlags.None); } }
public void write(VideoLib.AudioFrame frame) { if (audioBuffer == null || frame.Length == 0) { return; } // store pts for this frame and the byte offset at which this frame is // written pts = frame.Pts; ptsPos = offsetBytes; int playPos, writePos; audioBuffer.GetCurrentPosition(out playPos, out writePos); if (playPos <= offsetBytes && offsetBytes < writePos) { log.Warn("playpos:" + playPos.ToString() + " offset:" + offsetBytes.ToString() + " writePos:" + writePos.ToString() + " dataSize:" + frame.Length.ToString()); offsetBytes = writePos; } audioBuffer.Write(frame.Data, 0, frame.Length, offsetBytes, LockFlags.None); offsetBytes = (offsetBytes + frame.Length) % bufferSizeBytes; if (audioState == AudioState.START_PLAY_AFTER_NEXT_WRITE) { audioBuffer.Play(0, PlayFlags.Looping); audioState = AudioState.PLAYING; } }
public void StartSound() { if (disposed) { throw new ObjectDisposedException("Sound"); } if (Global.Config.SoundEnabled == false) { return; } if (DSoundBuffer == null) { return; } if (IsPlaying) { return; } needDiscard = true; DSoundBuffer.Write(SoundBuffer, 0, LockFlags.EntireBuffer); DSoundBuffer.CurrentPlayPosition = 0; DSoundBuffer.Play(0, PlayFlags.Looping); }
public void play(VideoLib.AudioFrame frame) { if (audioBuffer == null || frame.Length == 0) { return; } // store pts for this frame and the byte offset at which this frame is // written pts = frame.Pts; ptsPos = offsetBytes; int playPos, writePos; audioBuffer.GetCurrentPosition(out playPos, out writePos); if (playPos <= offsetBytes && offsetBytes < writePos) { //log.Warn("playpos:" + playPos.ToString() + " offset:" + offsetBytes.ToString() + " writePos:" + writePos.ToString() + " dataSize:" + frame.Length.ToString()); offsetBytes = writePos; } audioBuffer.Write(frame.Data, 0, frame.Length, offsetBytes, LockFlags.None); offsetBytes = (offsetBytes + frame.Length) % bufferSizeBytes; if (Status == BufferStatus.None) { // start playing audioBuffer.Play(0, PlayFlags.Looping); } //System.Diagnostics.Debug.Print("AudioClock:" + getAudioClock().ToString()); }
private void PlaySound(Stream sound) { DirectSound ds = new DirectSound(); ds.SetCooperativeLevel(this.Handle, CooperativeLevel.Priority); WaveFormat format = WaveFormat.CreateCustomFormat( WaveFormatEncoding.Pcm, 44100, 2, 4 * 44100, 4, 16 ); SoundBufferDescription primaryDesc = new SoundBufferDescription(); primaryDesc.Format = format; primaryDesc.Flags = BufferFlags.GlobalFocus; primaryDesc.BufferBytes = 8 * 4 * 44100; PrimarySoundBuffer pBuffer = new PrimarySoundBuffer(ds, primaryDesc); SoundBufferDescription secondDesc = new SoundBufferDescription(); secondDesc.Format = format; secondDesc.Flags = BufferFlags.GlobalFocus | BufferFlags.ControlPositionNotify | BufferFlags.GetCurrentPosition2; secondDesc.BufferBytes = 8 * 4 * 44100; SecondarySoundBuffer secondBuffer = new SecondarySoundBuffer(ds, secondDesc); secondBuffer.Write(sound.ReadAll(), 0, LockFlags.None); secondBuffer.Play(0, PlayFlags.None); }
public void MainLoop(int samples, bool reverse)//Write cursor is basically useless, need to keep track of own write position and hope it lines up with playback. With proper Sync algo it should be acceptable. { short[] smallBuf = new short[samples]; for (int i = 0; i < samples; i++) { smallBuf[i] = buffer[i]; } if (bufferOffset + samples + 1 > bufferSize) { int spaceLeft = bufferSize - (bufferOffset + 1); sBuffer.Write(smallBuf, 0, spaceLeft, bufferOffset * 2, LockFlags.None); sBuffer.Write(smallBuf, spaceLeft, samples - spaceLeft, 0, LockFlags.None); bufferOffset = spaceLeft; flip = true; } else { sBuffer.Write(smallBuf, 0, samples, bufferOffset * 2, LockFlags.None); bufferOffset += samples; flip = false; } if (sBuffer.Status != (BufferStatus.Looping | BufferStatus.Playing)) { sBuffer.Play(0, PlayFlags.Looping); } lastLastWritePos = lastWritePos; lastWritePos = sBuffer.CurrentWritePosition; lastSamples = samples; }
void InitDirectSound(Control parent) { //Create the device MyNesDEBUGGER.WriteLine(this, "Initializing direct sound for APU", DebugStatus.None); _SoundDevice = new DirectSound(); _SoundDevice.SetCooperativeLevel(parent.Parent.Handle, CooperativeLevel.Normal); //Create the wav format WaveFormat wav = new WaveFormat(); wav.FormatTag = WaveFormatTag.Pcm; wav.SamplesPerSecond = 44100; wav.Channels = (short)(STEREO ? 2 : 1); AD = (STEREO ? 4 : 2);//Stereo / Mono wav.BitsPerSample = 16; wav.AverageBytesPerSecond = wav.SamplesPerSecond * wav.Channels * (wav.BitsPerSample / 8); wav.BlockAlignment = (short)(wav.Channels * wav.BitsPerSample / 8); BufferSize = wav.AverageBytesPerSecond; //Description SoundBufferDescription des = new SoundBufferDescription(); des.Format = wav; des.SizeInBytes = BufferSize; //des.Flags = BufferFlags.GlobalFocus | BufferFlags.Software; des.Flags = BufferFlags.ControlVolume | BufferFlags.ControlFrequency | BufferFlags.ControlPan | BufferFlags.ControlEffects; //buffer DATA = new byte[BufferSize]; buffer = new SecondarySoundBuffer(_SoundDevice, des); buffer.Play(0, PlayFlags.Looping); //channels InitChannels(); MyNesDEBUGGER.WriteLine(this, "APU OK !!", DebugStatus.Cool); }
static void Main(string[] args) { DirectSound directSound = new DirectSound(); var form = new Form(); form.Text = "SharpDX - DirectSound Demo"; // Set Cooperative Level to PRIORITY (priority level can call the SetFormat and Compact methods) // directSound.SetCooperativeLevel(form.Handle, CooperativeLevel.Priority); // Create PrimarySoundBuffer var primaryBufferDesc = new SoundBufferDescription(); primaryBufferDesc.Flags = BufferFlags.PrimaryBuffer; primaryBufferDesc.AlgorithmFor3D = Guid.Empty; var primarySoundBuffer = new PrimarySoundBuffer(directSound, primaryBufferDesc); // Play the PrimarySound Buffer primarySoundBuffer.Play(0, PlayFlags.Looping); // Default WaveFormat Stereo 44100 16 bit WaveFormat waveFormat = new WaveFormat(); // Create SecondarySoundBuffer var secondaryBufferDesc = new SoundBufferDescription(); secondaryBufferDesc.BufferBytes = waveFormat.ConvertLatencyToByteSize(60000); secondaryBufferDesc.Format = waveFormat; secondaryBufferDesc.Flags = BufferFlags.GetCurrentPosition2 | BufferFlags.ControlPositionNotify | BufferFlags.GlobalFocus | BufferFlags.ControlVolume | BufferFlags.StickyFocus; secondaryBufferDesc.AlgorithmFor3D = Guid.Empty; var secondarySoundBuffer = new SecondarySoundBuffer(directSound, secondaryBufferDesc); // Get Capabilties from secondary sound buffer var capabilities = secondarySoundBuffer.Capabilities; // Lock the buffer DataStream dataPart2; var dataPart1 =secondarySoundBuffer.Lock(0, capabilities.BufferBytes, LockFlags.EntireBuffer, out dataPart2); // Fill the buffer with some sound int numberOfSamples = capabilities.BufferBytes/waveFormat.BlockAlign; for (int i = 0; i < numberOfSamples; i++) { double vibrato = Math.Cos(2 * Math.PI * 10.0 * i /waveFormat.SampleRate); short value = (short) (Math.Cos(2*Math.PI*(220.0 + 4.0 * vibrato)*i/waveFormat.SampleRate)*16384); // Not too loud dataPart1.Write(value); dataPart1.Write(value); } // Unlock the buffer secondarySoundBuffer.Unlock(dataPart1, dataPart2); // Play the song secondarySoundBuffer.Play(0, PlayFlags.Looping); Application.Run(form); }
bool PlayWaveFile() { try { secondaryBuffer.CurrentPosition = 0; secondaryBuffer.Volume = Volume.Maximum; secondaryBuffer.Play(0, PlayFlags.None); } catch { return(false); } return(true); }
public static void PlaySound(SecondarySoundBuffer Sound, bool bCloseFirst, bool bLoopSound) { //stop currently playing waves? if (bCloseFirst) { Sound.Stop(); Sound.CurrentPosition = 0; } //loop the sound? if (bLoopSound) { Sound.Play(0, SharpDX.DirectSound.PlayFlags.Looping); } else { Sound.Play(0, SharpDX.DirectSound.PlayFlags.None); } }
static void Main(string[] args) { Console.WriteLine("1 - Direct sound"); Console.WriteLine("2 - Windows media player"); Console.WriteLine("Twój wybór:"); string wartosc = Console.ReadLine(); if (wartosc == "1") { Console.Write("Podaj nazwe pliku z pulpitu: "); string nazwa_pliku = Console.ReadLine(); var path = "C:\\Users\\lab\\Desktop\\" + nazwa_pliku; DirectSound directSound = new DirectSound(); var primaryBufferDesc = new SoundBufferDescription(); primaryBufferDesc.Flags = BufferFlags.PrimaryBuffer; var primarySoundBuffer = new PrimarySoundBuffer(directSound, primaryBufferDesc); primarySoundBuffer.Play(0, PlayFlags.Looping); WaveFormat waveFormat = new WaveFormat(); var secondaryBufferDesc = new SoundBufferDescription(); secondaryBufferDesc.BufferBytes = waveFormat.ConvertLatencyToByteSize(60000); secondaryBufferDesc.Format = waveFormat; secondaryBufferDesc.Flags = BufferFlags.GetCurrentPosition2 | BufferFlags.ControlPositionNotify | BufferFlags.GlobalFocus | BufferFlags.ControlVolume | BufferFlags.StickyFocus; secondaryBufferDesc.AlgorithmFor3D = Guid.Empty; var secondarySoundBuffer = new SecondarySoundBuffer(directSound, secondaryBufferDesc); var capabilities = secondarySoundBuffer.Capabilities; //Stream stream = File.Open(path, FileMode.Open); //byte[] arrayTest = ReadFully(stream); byte[] array = File.ReadAllBytes(path); DataStream dataPart2; var dataPart1 = secondarySoundBuffer.Lock(0, capabilities.BufferBytes, LockFlags.EntireBuffer, out dataPart2); dataPart1.Read(array, 0, array.Length); int numberOfSamples = capabilities.BufferBytes / waveFormat.BlockAlign; for (int i = 0; i < numberOfSamples; i++) { double vibrato = Math.Cos(2 * Math.PI * 10.0 * i / waveFormat.SampleRate); short value = (short)(Math.Cos(2 * Math.PI * (220.0 + 4.0 * vibrato) * i / waveFormat.SampleRate) * 16384); // Not too loud dataPart1.Write(value); } secondarySoundBuffer.Unlock(dataPart1, dataPart2); secondarySoundBuffer.Play(0, PlayFlags.None); } else { Console.Write("Podaj nazwe pliku z pulpitu: "); string nazwa_pliku = Console.ReadLine(); player = new WindowsMediaPlayer(); player.URL = "C:\\Users\\lab\\Desktop\\" + nazwa_pliku; player.controls.play(); } }
public void run() { directSound = new DirectSound(); IntPtr hwnd = GetDesktopWindow(); // Set Cooperative Level to PRIORITY (priority level can call the SetFormat and Compact methods) directSound.SetCooperativeLevel(hwnd, CooperativeLevel.Priority); // Create PrimarySoundBuffer var primaryBufferDesc = new SoundBufferDescription(); primaryBufferDesc.Flags = BufferFlags.PrimaryBuffer; primaryBufferDesc.AlgorithmFor3D = Guid.Empty; primarySoundBuffer = new PrimarySoundBuffer(directSound, primaryBufferDesc); // Create SecondarySoundBuffer int soundLatencyInMilliseconds = 100; var secondaryBufferDesc = new SoundBufferDescription(); secondaryBufferDesc.BufferBytes = soundStreamer.waveFormat.ConvertLatencyToByteSize(soundLatencyInMilliseconds); secondaryBufferDesc.Format = soundStreamer.waveFormat; secondaryBufferDesc.Flags = BufferFlags.GetCurrentPosition2 | BufferFlags.ControlPositionNotify | BufferFlags.GlobalFocus | BufferFlags.ControlVolume | BufferFlags.StickyFocus | BufferFlags.Trueplayposition; secondaryBufferDesc.AlgorithmFor3D = Guid.Empty; secondarySoundBuffer = new SecondarySoundBuffer(directSound, secondaryBufferDesc); NotificationPosition n = new NotificationPosition(); n.Offset = (secondaryBufferDesc.BufferBytes / 4) * 1; n.WaitHandle = soundStreamer.wait; NotificationPosition n2 = new NotificationPosition(); n2.Offset = (secondaryBufferDesc.BufferBytes / 4) * 3; n2.WaitHandle = soundStreamer.wait; secondarySoundBuffer.SetNotificationPositions(new NotificationPosition[] { n, n2 }); soundStreamerThread = new Thread(soundStreamer.loop); soundStreamer.secondarySoundBuffer = secondarySoundBuffer; soundStreamerThread.Start(); // play the sound secondarySoundBuffer.Play(0, PlayFlags.Looping); }
//--------------------// #region Playback /// <summary> /// Starts the sound playback /// </summary> public virtual void StartPlayback(bool looping) { #region Sanity checks if (IsDisposed) { throw new ObjectDisposedException(ToString()); } #endregion SoundBuffer.Play(0, looping ? PlayFlags.Looping : PlayFlags.None); }
/// <summary> /// Starts playing the current buffer. /// </summary> /// public void Play(float[] samples) { if (isPlaying) { return; } // Start playing and exit. buffer.Write(samples, 0, LockFlags.None); new Thread(() => { OnFramePlayingStarted(new PlayFrameEventArgs(0, samples.Length)); buffer.Play(0, PlayFlags.None); waitHandles[secondHalfBufferIndex].WaitOne(); OnStopped(EventArgs.Empty); }).Start(); }
void NotifyThread() { var temp = new byte[mNotifySize]; int offset = 0; try { while (isRunning) { mNotificationEvent.WaitOne(); int playpos = scdBuffer.CurrentPlayPosition; //读指针(读取数据开端) int wrpos = scdBuffer.CurrentWritePosition; // 写指针(读取数据结尾) //while (PlayBuf.Count < mNotifySize) ; if (playBuf.Count >= mNotifySize) { playBuf.CopyTo(0, temp, 0, mNotifySize); playBuf.RemoveRange(0, mNotifySize); scdBuffer.Write(temp, 0, mNotifySize, offset * mNotifySize, LockFlags.None); // App.log.InfoFormat("声音....{0},{1},{2}", playpos, wrpos, playBuf.Count); } else { Array.Clear(temp, 0, temp.Length); scdBuffer.Write(temp, 0, mNotifySize, offset * mNotifySize, LockFlags.None); App.log.InfoFormat("声音数据不连续....{0},{1},{2}", playpos, wrpos, playBuf.Count); } scdBuffer.Play(0, PlayFlags.Looping); Console.WriteLine("Second: " + DateTime.Now.Second); offset = (offset + 1) % cNotifyNum; } } catch (ThreadAbortException) { device.Dispose(); mNotificationEvent.Dispose(); } }
public Sound(IntPtr handle) { test[1] = test[0] + 2; test[2] = test[1] + 2; test[3] = test[2] + 1; test[4] = test[3] + 2; test[5] = test[4] + 2; test[6] = test[5] + 2; DirectSound directSound = new DirectSound(); // Set Cooperative Level to PRIORITY (priority level can call the SetFormat and Compact methods) // directSound.SetCooperativeLevel(handle, CooperativeLevel.Priority); // Create PrimarySoundBuffer var primaryBufferDesc = new SoundBufferDescription(); primaryBufferDesc.Flags = BufferFlags.PrimaryBuffer; primaryBufferDesc.AlgorithmFor3D = Guid.Empty; var primarySoundBuffer = new PrimarySoundBuffer(directSound, primaryBufferDesc); // Play the PrimarySound Buffer primarySoundBuffer.Play(0, PlayFlags.Looping); // Default WaveFormat Stereo 44100 16 bit waveFormat = new WaveFormat(); // Create SecondarySoundBuffer var secondaryBufferDesc = new SoundBufferDescription(); secondaryBufferDesc.BufferBytes = waveFormat.ConvertLatencyToByteSize(10000); secondaryBufferDesc.Format = waveFormat; secondaryBufferDesc.Flags = BufferFlags.GetCurrentPosition2 | BufferFlags.ControlPositionNotify | BufferFlags.GlobalFocus | BufferFlags.ControlVolume | BufferFlags.StickyFocus; secondaryBufferDesc.AlgorithmFor3D = Guid.Empty; secondarySoundBuffer = new SecondarySoundBuffer(directSound, secondaryBufferDesc); // Get Capabilties from secondary sound buffer capabilities = secondarySoundBuffer.Capabilities; sounds = new short[capabilities.BufferBytes / waveFormat.BlockAlign]; // Play the song secondarySoundBuffer.Play(0, PlayFlags.Looping); for (int i = 0; i < sounds.Length; i++) { sounds[i] = 0; } }
/// <summary> /// Plays the currently configured sound /// </summary> public void Play(PlayingDone delegateHandler) { switch (looped) { case true: // do not create a worker thread if (soundPlayer != null) { soundPlayer.CurrentPlayPosition = 0; soundPlayer.Play(0, PlayFlags.Looping); } break; case false: // create a worker thread that gives a notification when the playback has completed if ((workerThread == null) || (!workerThread.IsAlive)) { playingDoneDelegate = delegateHandler; workerThread = new Thread(_playThread); workerThread.Start(); } break; } }
public void Play() { if (!IsPaused) { return; } if (buffer != null && !buffer.Disposed & !IsRendering) { IsPaused = false; try//Sometimes this line thorws an exception for unkown reason !! { buffer.Play(0, PlayFlags.Looping); } catch { } } }
public void Play() { if (!IsPaused) { return; } if (isInitialized) { IsPaused = false; // Reset buffer pointers buffer_internal_r_pos = buffer_internal_w_pos - latency_in_samples; buffer.Play(0, PlayFlags.Looping); } }
public void StartSound() { BufferSizeSamples = Sound.MillisecondsToSamples(Global.Config.SoundBufferSizeMs); // 35 to 65 milliseconds depending on how big the buffer is. This is a trade-off // between more frequent but less severe glitches (i.e. catching underruns before // they happen and filling the buffer with silence) or less frequent but more // severe glitches. At least on my Windows 8 machines, the distance between the // play and write cursors can be up to 30 milliseconds, so that would be the // absolute minimum we could use here. int minBufferFullnessMs = Math.Min(35 + ((Global.Config.SoundBufferSizeMs - 60) / 2), 65); MaxSamplesDeficit = BufferSizeSamples - Sound.MillisecondsToSamples(minBufferFullnessMs); var format = new WaveFormat { SamplesPerSecond = Sound.SampleRate, BitsPerSample = Sound.BytesPerSample * 8, Channels = Sound.ChannelCount, FormatTag = WaveFormatTag.Pcm, BlockAlignment = Sound.BlockAlign, AverageBytesPerSecond = Sound.SampleRate * Sound.BlockAlign }; var desc = new SoundBufferDescription { Format = format, Flags = BufferFlags.GlobalFocus | BufferFlags.Software | BufferFlags.GetCurrentPosition2 | BufferFlags.ControlVolume, SizeInBytes = BufferSizeBytes }; _deviceBuffer = new SecondarySoundBuffer(_device, desc); _actualWriteOffsetBytes = -1; _filledBufferSizeBytes = 0; _lastWriteTime = 0; _lastWriteCursor = 0; _deviceBuffer.Play(0, PlayFlags.Looping); }
protected override bool PlayAudioFile() { try { // Set the position at the beginning of the sound buffer. _SecondaryBuffer.CurrentPosition = 0; // Set volume of the buffer to 100% //_SecondaryBuffer.Volume = 100; // Play the contents of the secondary sound buffer. _SecondaryBuffer.Play(0, PlayFlags.None); } catch { return(false); } return(true); }
private unsafe void WavePlayThreadProc() { try { _soundBuffer.Play(0, DSBPLAY_FLAGS.LOOPING); const int sampleSize = 4; var rawBufferLength = _bufferSize * sampleSize; var hBuffer = Marshal.AllocHGlobal(rawBufferLength); NativeHelper.INITBLK((void *)hBuffer, 0, rawBufferLength); try { var lastWrittenBuffer = -1; do { _fillEvent.WaitOne(); var nextIndex = (lastWrittenBuffer + 1) % _bufferCount; var playPos = _soundBuffer.PlayPosition % (_bufferCount * rawBufferLength); var playingIndex = playPos / rawBufferLength; for (var i = nextIndex; i != playingIndex && !_isFinished; i = ++i % _bufferCount) { if (!OnBufferRequest((uint *)hBuffer, _bufferSize)) { NativeHelper.INITBLK((void *)hBuffer, 0, rawBufferLength); } var writePos = i * rawBufferLength; _soundBuffer.Write(writePos, (void *)hBuffer, rawBufferLength, DSBLOCK.None); lastWrittenBuffer = i; } } while (!_isFinished); } finally { Marshal.FreeHGlobal(hBuffer); _soundBuffer.Stop(); } } catch (Exception ex) { Logger.Error(ex); } }
public void UpdateFlags() { for (int i = BufferList.Count - 1; i >= 0; i--) { SecondarySoundBuffer buffer = CreateBuffer(); buffer.CurrentPlayPosition = BufferList[0].CurrentPlayPosition; if ((BufferList[0].Status & BufferStatus.Playing) == BufferStatus.Playing) { buffer.Play(0, Loop ? PlayFlags.Looping : PlayFlags.None); } if (!BufferList[0].Disposed) { BufferList[0].Dispose(); } BufferList.RemoveAt(0); } }
private void PlayAudio() { if (!IsError && !IsAborted) { try { //= - сэмпл был записан в буфер, но он еще не играл if (CurrentSample <= TotalSamples) { CheckBufferIsLost(true); AudioBuffer.Play(0, PlayFlags.Looping); ResetAudio = true; playing_a.Set(); } } catch (Exception ex) { SetError(ex); } } }
public void Initialize(IntPtr handle) { LoadSettings(); //Create the device Console.WriteLine("DirectSound: Initializing directSound ..."); _SoundDevice = new DirectSound(); _SoundDevice.SetCooperativeLevel(handle, CooperativeLevel.Normal); //Create the wav format WaveFormat wav = new WaveFormat(); wav.FormatTag = WaveFormatTag.Pcm; wav.SamplesPerSecond = Program.Settings.Audio_Frequency; wav.Channels = 1; wav.BitsPerSample = Program.Settings.Audio_BitsPerSample; wav.AverageBytesPerSecond = wav.SamplesPerSecond * wav.Channels * (wav.BitsPerSample / 8); wav.BlockAlignment = (short)(wav.Channels * wav.BitsPerSample / 8); BufferSize = (int)(wav.AverageBytesPerSecond * ((double)Program.Settings.Audio_BufferSizeInMilliseconds) / (double)1000); latency_in_bytes = (int)((double)wav.AverageBytesPerSecond * (double)(Program.Settings.Audio_LatencyInMilliseconds / (double)1000)); Console.WriteLine("DirectSound: BufferSize = " + BufferSize + " Byte"); Console.WriteLine("DirectSound: Latency in bytes = " + latency_in_bytes + " Byte"); //Description SoundBufferDescription des = new SoundBufferDescription(); des.Format = wav; des.SizeInBytes = BufferSize; des.Flags = BufferFlags.ControlVolume | BufferFlags.ControlFrequency | BufferFlags.ControlPan | BufferFlags.Software; buffer = new SecondarySoundBuffer(_SoundDevice, des); buffer.Play(0, PlayFlags.Looping); // Set volume SetVolume(volume); Console.WriteLine("DirectSound: DirectSound initialized OK."); canRender = true; }
public void Play(double spedmodification) { _speedmod = spedmodification; ClearBuffer(); _bfpos = 0; if (_requestproc != null) { for (int i = 0; i < 3; i++) { int timems; short[] data = _requestproc.Invoke(out timems); if (data != null && data.Length > 0) { WriteNextData(data, timems); } } } _soundBuffer.CurrentPosition = 0; _samplesPlayed = 0; _soundBuffer.Frequency = (int)(spedmodification * _buffDescription.Format.SampleRate); _soundBuffer.Play(0, PlayFlags.Looping); }
private static void Play(double frequency, double duration, int iType) { Initialise(); try { int sampleCount = (int)(duration * waveFormat.SamplesPerSecond); // buffer description SoundBufferDescription soundBufferDescription = new SoundBufferDescription(); soundBufferDescription.Format = waveFormat; soundBufferDescription.Flags = BufferFlags.Defer; soundBufferDescription.SizeInBytes = sampleCount * waveFormat.BlockAlignment; SecondarySoundBuffer secondarySoundBuffer = new SecondarySoundBuffer(directSound, soundBufferDescription); short[] rawsamples = new short[sampleCount]; double frac, value; switch (iType) { case 1: //Sinusoidal for (int i = 0; i < sampleCount; i++) { frac = frequency * duration * i / (double)sampleCount; value = System.Math.Sin(2.0 * System.Math.PI * frac); rawsamples[i] = (short)(amplitude * value); } break; case 2: //Square for (int i = 0; i < sampleCount; i++) { frac = frequency * duration * i / (double)sampleCount; frac = frac - (int)frac; value = frac < 0.5 ? -1.0 : 1.0; rawsamples[i] = (short)(amplitude * value); } break; } //load audio samples to secondary buffer secondarySoundBuffer.Write(rawsamples, 0, LockFlags.EntireBuffer); //play audio buffer secondarySoundBuffer.Play(0, PlayFlags.None); //wait to complete before returning while ((secondarySoundBuffer.Status & BufferStatus.Playing) != 0); secondarySoundBuffer.Dispose(); } catch (Exception ex) { TextWindow.WriteLine(ex.Message); } }
void InitDirectSound(IntPtr handle) { //Create the device _SoundDevice = new DirectSound(); _SoundDevice.SetCooperativeLevel(handle, CooperativeLevel.Priority); //Creat the wav format, it will be mono-44100-pcm-16bit //TODO: support more wave formats WaveFormat wav = new WaveFormat(); wav.FormatTag = WaveFormatTag.Pcm; wav.SamplesPerSecond = 44100; wav.Channels = 1;//mono wav.BitsPerSample = 16; wav.AverageBytesPerSecond = 88200;//wav.SamplesPerSecond * wav.Channels * (wav.BitsPerSample / 8); wav.BlockAlignment = 2;//(wfx.Channels * wfx.BitsPerSample / 8); BufferSize = 88200 * 5; //Description SoundBufferDescription des = new SoundBufferDescription(); des.Format = wav; des.SizeInBytes = BufferSize; des.Flags = BufferFlags.GlobalFocus | BufferFlags.Software; //buffer buffer = new SecondarySoundBuffer(_SoundDevice, des); DATA = new byte[BufferSize]; buffer.Play(0, PlayFlags.Looping); //channels InitChannels(); }
/// <summary> /// Play DX7. /// </summary> /// <param name="channels">An array of values for each channel (values between 0 and 1, usually 8 channels).</param> public static void PlayDX7(Primitive channels) { Initialise(); try { int i, iServo; double duration = 0.0225; int sampleCount = (int)(duration * waveFormat.SamplesPerSecond); // buffer description SoundBufferDescription soundBufferDescription = new SoundBufferDescription(); soundBufferDescription.Format = waveFormat; soundBufferDescription.Flags = BufferFlags.Defer; soundBufferDescription.SizeInBytes = sampleCount * waveFormat.BlockAlignment; SecondarySoundBuffer secondarySoundBuffer = new SecondarySoundBuffer(directSound, soundBufferDescription); short[] rawsamples = new short[sampleCount]; int stopSamples = (int)(0.0004 * waveFormat.SamplesPerSecond); List<int> servoSamples = new List<int>(); Primitive indices = SBArray.GetAllIndices(channels); int servoCount = SBArray.GetItemCount(indices); for (iServo = 1; iServo <= servoCount; iServo++) { servoSamples.Add((int)((0.0007 + 0.0008 * channels[indices[iServo]]) * waveFormat.SamplesPerSecond)); } //Lead-in int leading = sampleCount - (servoCount + 1) * stopSamples - servoSamples.Sum(); int sample = 0; for (i = 0; i < leading; i++) rawsamples[sample++] = 0; //Servos for (i = 0; i < stopSamples; i++) rawsamples[sample++] = (short)(-amplitude); for (iServo = 0; iServo < servoCount; iServo++) { for (i = 0; i < servoSamples[iServo]; i++) rawsamples[sample++] = amplitude; for (i = 0; i < stopSamples; i++) rawsamples[sample++] = (short)(-amplitude); } //load audio samples to secondary buffer secondarySoundBuffer.Write(rawsamples, 0, LockFlags.EntireBuffer); //play audio buffer secondarySoundBuffer.Play(0, PlayFlags.None); //wait to complete before returning while ((secondarySoundBuffer.Status & BufferStatus.Playing) != 0); secondarySoundBuffer.Dispose(); } catch (Exception ex) { TextWindow.WriteLine(ex.Message); } }
private void InitDirectSound(Control parent) { Debug.WriteLine(this, "Initializing APU ....", DebugStatus.None); //Create the device _SoundDevice = new DirectSound(); _SoundDevice.SetCooperativeLevel(parent.Parent.Handle, CooperativeLevel.Normal); //Create the wav format var wav = new WaveFormat(); wav.FormatTag = WaveFormatTag.Pcm; wav.SamplesPerSecond = 44100; wav.Channels = (short) (STEREO ? 2 : 1); AD = (STEREO ? 4 : 2); //Stereo / Mono wav.BitsPerSample = 16; wav.AverageBytesPerSecond = wav.SamplesPerSecond*wav.Channels*(wav.BitsPerSample/8); wav.BlockAlignment = (short) (wav.Channels*wav.BitsPerSample/8); BufferSize = wav.AverageBytesPerSecond; //Description var des = new SoundBufferDescription { Format = wav, SizeInBytes = BufferSize, Flags = BufferFlags.ControlVolume | BufferFlags.ControlFrequency | BufferFlags.ControlPan | BufferFlags.ControlEffects }; //des.Flags = BufferFlags.GlobalFocus | BufferFlags.Software; //buffer DATA = new byte[BufferSize]; buffer = new SecondarySoundBuffer(_SoundDevice, des); buffer.Play(0, PlayFlags.Looping); //channels InitChannels(); Debug.WriteLine(this, "APU initialized ok !!", DebugStatus.Cool); }
public void StartSound() { BufferSizeSamples = Sound.MillisecondsToSamples(Global.Config.SoundBufferSizeMs); // 35 to 65 milliseconds depending on how big the buffer is. This is a trade-off // between more frequent but less severe glitches (i.e. catching underruns before // they happen and filling the buffer with silence) or less frequent but more // severe glitches. At least on my Windows 8 machines, the distance between the // play and write cursors can be up to 30 milliseconds, so that would be the // absolute minimum we could use here. int minBufferFullnessMs = Math.Min(35 + ((Global.Config.SoundBufferSizeMs - 60) / 2), 65); MaxSamplesDeficit = BufferSizeSamples - Sound.MillisecondsToSamples(minBufferFullnessMs); var format = new WaveFormat { SamplesPerSecond = Sound.SampleRate, BitsPerSample = Sound.BytesPerSample * 8, Channels = Sound.ChannelCount, FormatTag = WaveFormatTag.Pcm, BlockAlignment = Sound.BlockAlign, AverageBytesPerSecond = Sound.SampleRate * Sound.BlockAlign }; var desc = new SoundBufferDescription { Format = format, Flags = BufferFlags.GlobalFocus | BufferFlags.Software | BufferFlags.GetCurrentPosition2 | BufferFlags.ControlVolume, SizeInBytes = BufferSizeBytes }; _deviceBuffer = new SecondarySoundBuffer(_device, desc); _actualWriteOffsetBytes = -1; _filledBufferSizeBytes = 0; _lastWriteTime = 0; _lastWriteCursor = 0; _deviceBuffer.Play(0, SlimDX.DirectSound.PlayFlags.Looping); }