bool InitializeDirectSound(IntPtr hwnd) { try { directSound = new SharpDX.DirectSound.DirectSound(); directSound.SetCooperativeLevel(hwnd, CooperativeLevel.Priority); var soundBufferDescription = new SoundBufferDescription { Flags = BufferFlags.PrimaryBuffer | BufferFlags.ControlVolume, BufferBytes = 0, Format = null, AlgorithmFor3D = Guid.Empty }; primaryBuffer = new PrimarySoundBuffer(directSound, soundBufferDescription); var samplesPerSec = 44100; var bitsPerSample = 16; var nChannels = 2; var blockAlign = bitsPerSample / 8 * nChannels; var nAvgBytesPerSec = samplesPerSec * blockAlign; var waveFormat = WaveFormat.CreateCustomFormat( WaveFormatEncoding.Pcm, samplesPerSec, nChannels, nAvgBytesPerSec, blockAlign, bitsPerSample ); primaryBuffer.Format = waveFormat; } catch { return(false); } return(true); }
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 InitializeBuffer(int rate, int channels) { format = new WaveFormat(); format.FormatTag = WaveFormatTag.Pcm; format.SamplesPerSecond = rate; format.BitsPerSample = 16; format.Channels = (short)channels; format.BlockAlignment = (short)(format.Channels * (format.BitsPerSample / 8)); format.AverageBytesPerSecond = format.SamplesPerSecond * format.BlockAlignment; BufferSize = format.AverageBytesPerSecond; BufferSize += 512 - (BufferSize % 512); buffer = new byte[BufferSize]; SoundBufferDescription description = new SoundBufferDescription(); description.Format = format; description.SizeInBytes = BufferSize; description.Flags = BufferFlags.ControlVolume | BufferFlags.GlobalFocus | BufferFlags.ControlPositionNotify; sbuffer = new SecondarySoundBuffer[2]; sbuffer[0] = new SecondarySoundBuffer(DirectSoundWrapper.Device, description); sbuffer[1] = new SecondarySoundBuffer(DirectSoundWrapper.Device, description); }
private void InitialiseDirectSound(IntPtr windowHandle, int sampleRate) { var waveFormat = new WaveFormat(sampleRate, 16, 2); _directSound = new DirectSound(); _directSound.SetCooperativeLevel(windowHandle, CooperativeLevel.Priority); var primaryBufferDescription = new SoundBufferDescription() { Flags = BufferFlags.PrimaryBuffer, AlgorithmFor3D = Guid.Empty, }; _primarySoundBuffer = new PrimarySoundBuffer(_directSound, primaryBufferDescription) { Format = waveFormat }; _soundBufferLength = waveFormat.ConvertLatencyToByteSize(500); var secondaryBufferDescription = new SoundBufferDescription() { Format = waveFormat, Flags = BufferFlags.GetCurrentPosition2 | BufferFlags.GlobalFocus, BufferBytes = _soundBufferLength, AlgorithmFor3D = Guid.Empty, }; _soundBuffer = new SecondarySoundBuffer(_directSound, secondaryBufferDescription); }
public SecondarySoundBuffer Acquire(int soundId) { if (soundId < 0 || soundId >= 4096) { return(null); } return((SecondarySoundBuffer)Archives.Sound.Open <SecondarySoundBuffer>(GetFilePath(soundId), stream => { SoundBufferDescription bufferDescription1 = new SoundBufferDescription(); bufferDescription1.Format = _waveFormat; bufferDescription1.BufferBytes = checked ((int)(stream.Length - 40L)); SoundBufferDescription bufferDescription2 = bufferDescription1; BufferFlags num1 = bufferDescription2.Flags | (BufferFlags)128; bufferDescription2.Flags = num1; SoundBufferDescription bufferDescription3 = bufferDescription1; BufferFlags num2 = bufferDescription3.Flags | (BufferFlags)32; bufferDescription3.Flags = num2; SoundBufferDescription bufferDescription4 = bufferDescription1; BufferFlags num3 = bufferDescription4.Flags | (BufferFlags)64; bufferDescription4.Flags = num3; SecondarySoundBuffer secondarySoundBuffer = new SecondarySoundBuffer(_soundDevice, bufferDescription1); stream.Seek(40L, SeekOrigin.Begin); byte[] buffer = new byte[stream.Length - 40L]; stream.Read(buffer, 0, buffer.Length); secondarySoundBuffer.Write(buffer, 0, (SharpDX.DirectSound.LockFlags) 2); return secondarySoundBuffer; })); }
public SoundLibrary(int index, string fileName, bool loop) { Index = index; fileName = Path.Combine(Settings.SoundPath, fileName); if (!File.Exists(fileName)) { return; } _stream = new WaveStream(fileName); _desc = new SoundBufferDescription { SizeInBytes = (int)_stream.Length, Flags = BufferFlags.ControlVolume | BufferFlags.ControlPan | BufferFlags.GlobalFocus, Format = _stream.Format }; _data = new byte[_desc.SizeInBytes]; _stream.Read(_data, 0, (int)_stream.Length); _loop = loop; _bufferList = new List <SecondarySoundBuffer>(); Play(); }
public Sound(IntPtr formHandle) { directSound = new DirectSound(); directSound.SetCooperativeLevel(formHandle, CooperativeLevel.Normal); // WAVEFORMATEX Structure (from Microsoft Documentation on DirectSound) // https://docs.microsoft.com/en-us/previous-versions/windows/desktop/ee419019(v%3dvs.85) var wFormatTag = WaveFormatEncoding.Pcm; var nSamplesPerSec = 44100; var nChannels = 1; var wBitsPerSample = 16; // (short) var nBlockAlign = (nChannels * wBitsPerSample) / 8; // nBlockAlign must be equal to the product of nChannels and wBitsPerSample divided by 8 (bits per byte) var nAvgBytesPerSec = nSamplesPerSec * nBlockAlign; // nAvgBytesPerSec should be equal to the product of nSamplesPerSec and nBlockAlign waveFormat = WaveFormat.CreateCustomFormat( tag: wFormatTag, sampleRate: nSamplesPerSec, channels: nChannels, averageBytesPerSecond: nAvgBytesPerSec, blockAlign: nBlockAlign, bitsPerSample: wBitsPerSample ); var bufferDesc = new SoundBufferDescription(); bufferDesc.Format = waveFormat; bufferDesc.BufferBytes = Convert.ToInt32( bufferDuration.TotalSeconds * waveFormat.AverageBytesPerSecond / waveFormat.Channels); buffer = new SecondarySoundBuffer(directSound, bufferDesc); int numSamples = buffer.Capabilities.BufferBytes / waveFormat.BlockAlign; samples = new short[numSamples]; }
public Sound(IntPtr handle, DirectSound device) { if (device != null) { device.SetCooperativeLevel(handle, CooperativeLevel.Priority); var format = new WaveFormat { SamplesPerSecond = 44100, BitsPerSample = 16, Channels = 2, FormatTag = WaveFormatTag.Pcm, BlockAlignment = 4 }; format.AverageBytesPerSecond = format.SamplesPerSecond * format.Channels * (format.BitsPerSample / 8); var desc = new SoundBufferDescription { Format = format, Flags = BufferFlags.GlobalFocus | BufferFlags.Software | BufferFlags.GetCurrentPosition2 | BufferFlags.ControlVolume, SizeInBytes = BufferSize }; DSoundBuffer = new SecondarySoundBuffer(device, desc); ChangeVolume(Global.Config.SoundVolume); } SoundBuffer = new byte[BufferSize]; disposed = false; }
protected void CreateSoundBuffer(int sampleRate, double bufferSizeSeconds) { // Buffer to use when marshalling the samples from an unmanaged pointer. // Give it a reasonable initial size, it will be resized dynamically if needed. _sampleBuffer = new short[4096]; // Setup the directsound buffer description var format = new WaveFormat(sampleRate, 16, 2); var buffer = new SoundBufferDescription(); buffer.Flags = BufferFlags.GlobalFocus | BufferFlags.ControlVolume; buffer.BufferBytes = (int)(format.AverageBytesPerSecond * bufferSizeSeconds); buffer.Format = format; buffer.AlgorithmFor3D = Guid.Empty; // Create a sound buffer with the specified buffer description. _secondaryBuffer = new SecondarySoundBuffer(_directSound, buffer); // Get the actual buffer size so we can keep // track of the current/next write position. _bufferBytes = _secondaryBuffer.Capabilities.BufferBytes; // When syncing to audio, we need samples per millisecond to estimate how // long to sleep for when waiting for enough free space in the playback buffer. _samplesPerMs = format.AverageBytesPerSecond / (sizeof(short) * 1000d); }
bool InitializeDirectSound(IntPtr windowHandler) { try { // Initialize the direct sound interface pointer for the default sound device. _DirectSound = new DirectSound(); // Set the cooperative level to priority so the format of the primary sound buffer can be modified. if (_DirectSound.SetCooperativeLevel(windowHandler, CooperativeLevel.Priority) != Result.Ok) { return(false); } // Setup the primary buffer description. var buffer = new SoundBufferDescription(); buffer.Flags = BufferFlags.PrimaryBuffer | BufferFlags.ControlVolume; buffer.AlgorithmFor3D = Guid.Empty; // Get control of the primary sound buffer on the default sound device. _PrimaryBuffer = new PrimarySoundBuffer(_DirectSound, buffer); // Setup the format of the primary sound buffer. // In this case it is a . _PrimaryBuffer.Format = new WaveFormat(44100, 16, 2); } catch (Exception) { return(false); } return(true); }
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); }
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); }
public DXWavePlayer(int device, int BufferByteSize, DataRequestDelegate fillProc) { if (BufferByteSize < 1000) { throw new ArgumentOutOfRangeException("BufferByteSize", "minimal size of buffer is 1000 bytes"); } _buffersize = BufferByteSize; _requestproc = fillProc; var devices = DirectSound.GetDevices(); if (device <= 0 || device >= devices.Count) { device = 0; } _outputDevice = new DirectSound(devices[device].DriverGuid); System.Windows.Interop.WindowInteropHelper wh = new System.Windows.Interop.WindowInteropHelper(Application.Current.MainWindow); _outputDevice.SetCooperativeLevel(wh.Handle, CooperativeLevel.Priority); _buffDescription = new SoundBufferDescription(); _buffDescription.Flags = BufferFlags.ControlPositionNotify | BufferFlags.ControlFrequency | BufferFlags.ControlEffects | BufferFlags.GlobalFocus | BufferFlags.GetCurrentPosition2; _buffDescription.BufferBytes = BufferByteSize * InternalBufferSizeMultiplier; WaveFormat format = new WaveFormat(16000, 16, 1); _buffDescription.Format = format; _soundBuffer = new SecondarySoundBuffer(_outputDevice, _buffDescription); _synchronizer = new AutoResetEvent(false); NotificationPosition[] nots = new NotificationPosition[InternalBufferSizeMultiplier]; NotificationPosition not; int bytepos = 800; for (int i = 0; i < InternalBufferSizeMultiplier; i++) { not = new NotificationPosition(); not.Offset = bytepos; not.WaitHandle = _synchronizer; nots[i] = not; bytepos += BufferByteSize; } _soundBuffer.SetNotificationPositions(nots); _waitThread = new Thread(new ThreadStart(DataRequestThread)) { Name = "MyWavePlayer.DataRequestThread" }; _waitThread.Start(); }
public void initialize(int samplesPerSecond, int bytesPerSample, int nrChannels, int bufferSizeBytes) { try { if (directSound == null) { directSound = new DirectSound(); directSound.SetCooperativeLevel(owner.Handle, CooperativeLevel.Priority); } releaseResources(); this.bufferSizeBytes = bufferSizeBytes; this.bytesPerSample = bytesPerSample; this.samplesPerSecond = samplesPerSecond; this.nrChannels = nrChannels; SoundBufferDescription desc = new SoundBufferDescription(); desc.BufferBytes = bufferSizeBytes; desc.Flags = BufferFlags.Defer | BufferFlags.GlobalFocus | BufferFlags.ControlVolume | BufferFlags.ControlFrequency | BufferFlags.GetCurrentPosition2; //desc.AlgorithmFor3D = Guid.Empty; int blockAlign = nrChannels * bytesPerSample; int averageBytesPerSecond = samplesPerSecond * blockAlign; WaveFormat format = WaveFormat.CreateCustomFormat(WaveFormatEncoding.Pcm, samplesPerSecond, nrChannels, averageBytesPerSecond, blockAlign, bytesPerSample * 8); desc.Format = format; silence = new char[bufferSizeBytes]; Array.Clear(silence, 0, silence.Length); audioBuffer = new SecondarySoundBuffer(directSound, desc); Volume = volume; offsetBytes = 0; prevPlayPos = 0; ptsPos = 0; prevPtsPos = 0; playLoops = 0; ptsLoops = 0; //log.Info("Direct Sound Initialized"); } catch (Exception e) { throw new VideoPlayerException("Error initializing Direct Sound: " + e.Message, e); } }
/// <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); } }
//--------------------// #region Engine /// <inheritdoc/> protected override void OnEngineSet() { base.OnEngineSet(); var description = new SoundBufferDescription { Flags = BufferFlags.ControlVolume }; _soundBuffer = new SecondarySoundBuffer(Engine.AudioDevice, description); }
private static string _PlayHarmonics(double frequency, double duration, Primitive harmonics) { try { Initialise(); int sampleCount = (int)(waveFormat.SamplesPerSecond / frequency); // buffer description SoundBufferDescription soundBufferDescription = new SoundBufferDescription(); soundBufferDescription.Format = waveFormat; soundBufferDescription.Flags = BufferFlags.Defer | BufferFlags.ControlVolume | BufferFlags.ControlPan; soundBufferDescription.SizeInBytes = sampleCount * waveFormat.BlockAlignment; SecondarySoundBuffer secondarySoundBuffer = new SecondarySoundBuffer(directSound, soundBufferDescription); secondarySoundBuffer.Pan = pan; secondarySoundBuffer.Volume = volume; short[] rawsamples = new short[sampleCount]; double frac, value; Primitive indices = SBArray.GetAllIndices(harmonics); int count = SBArray.GetItemCount(harmonics); for (int i = 0; i < sampleCount; i++) { frac = i / (double)sampleCount; value = System.Math.Sin(2.0 * System.Math.PI * frac); for (int j = 1; j <= count; j++) { double harmonic = indices[j]; value += harmonics[harmonic] * System.Math.Sin(2.0 * System.Math.PI * harmonic * frac); } rawsamples[i] = (short)(amplitude * value); } secondarySoundBuffer.Write(rawsamples, 0, LockFlags.EntireBuffer); string name = NextName(); Buffer buffer = new Buffer(name, secondarySoundBuffer, frequency, duration); buffers.Add(buffer); Thread thread = new Thread(new ParameterizedThreadStart(DoPlay)); thread.Start(buffer); if (!bAsync) { thread.Join(); } return(name); } catch (Exception ex) { Utilities.OnError(Utilities.GetCurrentMethod(), ex); return(""); } }
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; } }
public static SecondarySoundBuffer LoadSound3d(string FileName, double MDistance, double MaxDistance, bool useFull3DEmulation) { if (isFromResource) { FileName = FileName.Split('.')[0]; } SoundBufferDescription BufferDesc = new SoundBufferDescription(); if (!File.Exists(FileName)) { throw new ArgumentException("The sound " + FileName + " could not be found."); } BufferDesc.Flags = SharpDX.DirectSound.BufferFlags.Control3D | SharpDX.DirectSound.BufferFlags.ControlVolume | SharpDX.DirectSound.BufferFlags.ControlFrequency //| SharpDX.DirectSound.BufferFlags.StickyFocus | SharpDX.DirectSound.BufferFlags.Mute3DAtMaxDistance; // if (useFull3DEmulation) //BufferDesc.AlgorithmFor3D = DirectSound3DAlgorithmGuid.FullHrt3DAlgorithm; SecondarySoundBuffer theBuffer = null; if (!isFromResource) { AudioFile wFile = new AudioFile(new FileStream(FileName, FileMode.Open)); byte[] final = wFile.getRawWaveData(); BufferDesc.Format = wFile.format(); BufferDesc.BufferBytes = final.Length; theBuffer = new SecondarySoundBuffer(objDS, BufferDesc); theBuffer.Write(final, 0, LockFlags.EntireBuffer); wFile.close(); } else { byte[] data = Encrypter.getData(FileName, pass); AudioFile wFile = new AudioFile(data); byte[] final = wFile.getRawWaveData(); BufferDesc.Format = wFile.format(); BufferDesc.BufferBytes = final.Length; theBuffer = new SecondarySoundBuffer(objDS, BufferDesc); theBuffer.Write(final, 0, LockFlags.EntireBuffer); wFile.close(); } SoundBuffer3D DS3DBuffer = new SoundBuffer3D(theBuffer); DS3DBuffer.MinDistance = (float)MDistance; DS3DBuffer.MaxDistance = (float)MaxDistance; DS3DBuffer.Dispose(); return(theBuffer); }
public DXSoundDevice(IntPtr handle, Guid device) { Handle = handle; Desc = new SoundBufferDescription(); Desc.Format = new WaveFormat(); Desc.Format.BitsPerSample = 16; Desc.Format.BlockAlignment = 2; Desc.Format.Channels = 1; Desc.Format.FormatTag = WaveFormatTag.Pcm; SignalResampler = new Resampler(1); InitDevice(device); }
public void Initialize(IntPtr handle) { if (isInitialized) { Dispose(); } isInitialized = false; 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); BufferSize = Program.Settings.Audio_BufferSizeInBytes; //latency_in_bytes = (int)((double)wav.AverageBytesPerSecond * (double)(Program.Settings.Audio_LatencyInPrecentage / (double)1000)); latency_in_bytes = (Program.Settings.Audio_LatencyInPrecentage * BufferSize) / 100; latency_in_samples = latency_in_bytes / 2; 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."); isInitialized = true; Shutdown(); }
public MotorAudio(Stream stream) { using (var AudioStream = new WaveStream(stream)) { SoundBufferDesc = new SoundBufferDescription { Format = AudioStream.Format, Flags = BufferFlags.ControlVolume | BufferFlags.ControlFrequency | BufferFlags.ControlPan | BufferFlags.GetCurrentPosition2, SizeInBytes = (int)AudioStream.Length }; RawAudioStream = new byte[SoundBufferDesc.SizeInBytes]; AudioStream.Read(RawAudioStream, 0, (int)AudioStream.Length); } }
//--------------------// #region Engine /// <inheritdoc/> protected override void OnEngineSet() { base.OnEngineSet(); var description = new SoundBufferDescription { Format = Asset.SoundFormat, SizeInBytes = (int)Asset.SoundData.Length, Flags = BufferFlags.ControlVolume | BufferFlags.Control3D }; SoundBuffer = new SecondarySoundBuffer(Engine.AudioDevice, description); var data = new byte[description.SizeInBytes]; Asset.SoundData.Read(data, 0, (int)Asset.SoundData.Length); SoundBuffer.Write(data, 0, LockFlags.None); }
private SecondarySoundBuffer CreateBuffer(string id, WaveStream wave) { SoundBufferDescription description = new SoundBufferDescription { SizeInBytes = (int)wave.Length, Flags = BufferFlags.ControlVolume, Format = wave.Format, }; SecondarySoundBuffer buffer = new SecondarySoundBuffer(dSound, description); byte[] data = new byte[description.SizeInBytes]; wave.Read(data, 0, description.SizeInBytes); buffer.Write(data, 0, LockFlags.None); cache[id] = buffer; return(buffer); }
/// <summary> /// Initializes the soundbuffers /// </summary> /// <param name="FileName">The filename from which to pull the data to initialize the /// soundbuffers</param> public MusicPlayer(Burntime.Platform.IO.File file) { this.Filename = file.Name; Burntime.Platform.Log.Debug("prepare to play " + Filename); oggStream = new OggVorbisFileStream(file.Stream); FullLength = (int)oggStream.Length; format = new WaveFormat(); format.FormatTag = WaveFormatTag.Pcm; format.SamplesPerSecond = oggStream.Info.Rate; format.BitsPerSample = 16; format.Channels = (short)oggStream.Info.Channels; format.BlockAlignment = (short)(format.Channels * (format.BitsPerSample / 8)); format.AverageBytesPerSecond = format.SamplesPerSecond * format.BlockAlignment; SoundBufferDescription description = new SoundBufferDescription(); description.Format = format; description.SizeInBytes = StreamBufferSize; //if ( GameForm.Instance.GameSettings.ForceSoftwareMusicMixing ) description.Flags = BufferFlags.ControlVolume | BufferFlags.GlobalFocus | BufferFlags.ControlPositionNotify | BufferFlags.GetCurrentPosition2 | BufferFlags.Software; //Create the buffer. buffer = new SecondarySoundBuffer(DirectSoundWrapper.Device, description); SecondaryBufferWritePosition = 0; this.UpdateVolume(); // Create a notification Event object, to fire at each notify position NotificationEvent = new AutoResetEvent(false); // Preset as much of the EndNotificationPosition array as possible to avoid doing it // in real-time. EndNotificationPosition[0].Event = NotificationEvent; PredictedEndIndex = (int)(oggStream.Length % StreamBufferSize); //[bytes] // ready to go: MoreWaveDataAvailable = true; State = BufferPlayState.Idle; Play(); }
//ustvari secondary buffer in mu da ta wave private void SetWave(Wave _wave) { byte[] _bytes = _wave.ToByteArray(); SoundBufferDescription _soundBufferDescription = new SoundBufferDescription(); _soundBufferDescription.Format = _wave.WaveFormat; _soundBufferDescription.SizeInBytes = _bytes.Length; _soundBufferDescription.Flags = BufferFlags.ControlVolume | BufferFlags.ControlFrequency | BufferFlags.ControlPan; this.secondarySoundBuffer = new SecondarySoundBuffer(this.directSound, _soundBufferDescription); this.secondarySoundBuffer.Write <byte>(_bytes, 0, LockFlags.EntireBuffer); this.secondarySoundBuffer.Frequency = _wave.WaveFormat.SamplesPerSecond; this.SetVolume(); this.SetBalance(); }
public AudioDevice(IntPtr hwnd) { // initialise directsound _directSound = new DirectSound(); _directSound.SetCooperativeLevel(hwnd, CooperativeLevel.Priority); // create primary sound buffer var primaryBufferDesc = new SoundBufferDescription { Flags = BufferFlags.PrimaryBuffer, AlgorithmFor3D = Guid.Empty }; _primarySoundBuffer = new PrimarySoundBuffer(_directSound, primaryBufferDesc) { Format = new WaveFormat(), }; }
/// <summary> /// Create a playable sound buffer from a WAV file /// </summary> /// <param name="Filename">The WAV file to load</param> /// <returns>Playable sound buffer</returns> public static SecondarySoundBuffer CreateSoundBufferFromWave(string Filename) { // Load wave file using (WaveStream waveFile = new WaveStream(Filename)) { SoundBufferDescription description = new SoundBufferDescription(); description.Format = waveFile.Format; description.SizeInBytes = (int)waveFile.Length; description.Flags = BufferFlags.ControlVolume | BufferFlags.GlobalFocus; // Create the buffer. SecondarySoundBuffer buffer = new SecondarySoundBuffer(device, description); byte[] data = new byte[description.SizeInBytes]; waveFile.Read(data, 0, (int)waveFile.Length); buffer.Write(data, 0, LockFlags.None); return(buffer); } }
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); }
/// <summary>Creates a sound.</summary> /// <param name="samples">A byte array containing the sample data (Mono 16-bit Signed samples).</param> /// <param name="frequency">The sample frequency in herz.</param> /// <param name="soundIndex">The index of the sound.</param> /// <param name="speakerSound">Whether the sound is a speaker sound otherwise it is a sampled sound.</param> /// <returns>The Sound.</returns> public override SoundSystem.Sound CreateSound(byte[] samples, int frequency, int soundIndex, bool speakerSound) { WaveFormat waveFormat = new WaveFormat(); waveFormat.FormatTag = WaveFormatTag.Pcm; waveFormat.Channels = (short) 1; waveFormat.SamplesPerSecond = frequency; waveFormat.BlockAlignment = (short) 2; waveFormat.AverageBytesPerSecond = frequency * 2; waveFormat.BitsPerSample = (short) 16; SoundBufferDescription soundBufferDescription = new SoundBufferDescription(); soundBufferDescription.Format = waveFormat; soundBufferDescription.Flags = BufferFlags.ControlVolume; soundBufferDescription.SizeInBytes = samples.Length; SecondarySoundBuffer secondarySoundBuffer = new SecondarySoundBuffer(_directSound, soundBufferDescription); secondarySoundBuffer.Write(samples, 0, LockFlags.EntireBuffer); return new SlimDXSound(secondarySoundBuffer); }
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(); }
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); }
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); } }
private static string _PlayHarmonics(double frequency, double duration, Primitive harmonics) { try { Initialise(); int sampleCount = (int)(waveFormat.SamplesPerSecond / frequency); // buffer description SoundBufferDescription soundBufferDescription = new SoundBufferDescription(); soundBufferDescription.Format = waveFormat; soundBufferDescription.Flags = BufferFlags.Defer | BufferFlags.ControlVolume | BufferFlags.ControlPan; soundBufferDescription.SizeInBytes = sampleCount * waveFormat.BlockAlignment; SecondarySoundBuffer secondarySoundBuffer = new SecondarySoundBuffer(directSound, soundBufferDescription); secondarySoundBuffer.Pan = pan; secondarySoundBuffer.Volume = volume; short[] rawsamples = new short[sampleCount]; double frac, value; Primitive indices = SBArray.GetAllIndices(harmonics); int count = SBArray.GetItemCount(harmonics); for (int i = 0; i < sampleCount; i++) { frac = i / (double)sampleCount; value = System.Math.Sin(2.0 * System.Math.PI * frac); for (int j = 1; j <= count; j++) { double harmonic = indices[j]; value += harmonics[harmonic] * System.Math.Sin(2.0 * System.Math.PI * harmonic * frac); } rawsamples[i] = (short)(amplitude * value); } secondarySoundBuffer.Write(rawsamples, 0, LockFlags.EntireBuffer); string name = NextName(); Buffer buffer = new Buffer(name, secondarySoundBuffer, frequency, duration); buffers.Add(buffer); Thread thread = new Thread(new ParameterizedThreadStart(DoPlay)); thread.Start(buffer); if (!bAsync) thread.Join(); return name; } catch (Exception ex) { Utilities.OnError(Utilities.GetCurrentMethod(), ex); return ""; } }
private static string _PlayWave(double frequency, double duration, Primitive waveform) { try { Initialise(); int sampleCount = (int)(waveFormat.SamplesPerSecond / frequency); // buffer description SoundBufferDescription soundBufferDescription = new SoundBufferDescription(); soundBufferDescription.Format = waveFormat; soundBufferDescription.Flags = BufferFlags.Defer | BufferFlags.ControlVolume | BufferFlags.ControlPan; soundBufferDescription.SizeInBytes = sampleCount * waveFormat.BlockAlignment; SecondarySoundBuffer secondarySoundBuffer = new SecondarySoundBuffer(directSound, soundBufferDescription); secondarySoundBuffer.Pan = pan; secondarySoundBuffer.Volume = volume; short[] rawsamples = new short[sampleCount]; double frac, value; Primitive indices = SBArray.GetAllIndices(waveform); int count = SBArray.GetItemCount(waveform); double interval = indices[count] - indices[1]; double[] timeFrac = new double[count]; double[] timeValue = new double[count]; for (int i = 1; i <= count; i++) //Normalise to interval 1; { timeFrac[i - 1] = (indices[i] - indices[1]) / interval; timeValue[i - 1] = waveform[indices[i]]; } for (int i = 0; i < sampleCount; i++) { frac = i / (double)sampleCount; frac = frac - (int)frac; for (int j = 0; j < count - 1; j++) { if (frac >= timeFrac[j] && frac <= timeFrac[j + 1]) { value = timeValue[j] + (timeValue[j + 1] - timeValue[j]) * (frac - timeFrac[j]) / (timeFrac[j + 1] - timeFrac[j]); rawsamples[i] = (short)(amplitude * value); break; } } } secondarySoundBuffer.Write(rawsamples, 0, LockFlags.EntireBuffer); string name = NextName(); Buffer buffer = new Buffer(name, secondarySoundBuffer, frequency, duration); buffers.Add(buffer); Thread thread = new Thread(new ParameterizedThreadStart(DoPlay)); thread.Start(buffer); if (!bAsync) thread.Join(); return name; } catch (Exception ex) { Utilities.OnError(Utilities.GetCurrentMethod(), ex); return ""; } }
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); }
private static string _Play(double frequency, double duration, int iType) { try { Initialise(); int sampleCount = (int)(waveFormat.SamplesPerSecond / frequency); // buffer description SoundBufferDescription soundBufferDescription = new SoundBufferDescription(); soundBufferDescription.Format = waveFormat; soundBufferDescription.Flags = BufferFlags.Defer | BufferFlags.ControlVolume | BufferFlags.ControlPan; soundBufferDescription.SizeInBytes = sampleCount * waveFormat.BlockAlignment; SecondarySoundBuffer secondarySoundBuffer = new SecondarySoundBuffer(directSound, soundBufferDescription); secondarySoundBuffer.Pan = pan; secondarySoundBuffer.Volume = volume; short[] rawsamples = new short[sampleCount]; double frac, value; switch (iType) { case 1: //Sinusoidal for (int i = 0; i < sampleCount; i++) { frac = 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 = i / (double)sampleCount; frac = frac - (int)frac; value = frac < 0.5 ? -1.0 : 1.0; rawsamples[i] = (short)(amplitude * value); } break; } secondarySoundBuffer.Write(rawsamples, 0, LockFlags.EntireBuffer); string name = NextName(); Buffer buffer = new Buffer(name, secondarySoundBuffer, frequency, duration); buffers.Add(buffer); Thread thread = new Thread(new ParameterizedThreadStart(DoPlay)); thread.Start(buffer); if (!bAsync) thread.Join(); return name; } catch (Exception ex) { Utilities.OnError(Utilities.GetCurrentMethod(), ex); return ""; } }
/// <summary> /// Constructs a new Audio Output Device. /// </summary> /// /// <param name="device">Global identifier of the audio output device.</param> /// <param name="owner">The owner window handle.</param> /// <param name="samplingRate">The sampling rate of the device.</param> /// <param name="channels">The number of channels of the device.</param> /// public AudioOutputDevice(Guid device, IntPtr owner, int samplingRate, int channels) { this.owner = owner; this.samplingRate = samplingRate; this.channels = channels; this.device = device; DirectSound ds = new DirectSound(device); ds.SetCooperativeLevel(owner, CooperativeLevel.Priority); // Set the output format WaveFormat waveFormat = new WaveFormat(); waveFormat.FormatTag = WaveFormatTag.IeeeFloat; waveFormat.BitsPerSample = 32; waveFormat.BlockAlignment = (short)(waveFormat.BitsPerSample * channels / 8); waveFormat.Channels = (short)channels; waveFormat.SamplesPerSecond = samplingRate; waveFormat.AverageBytesPerSecond = waveFormat.SamplesPerSecond * waveFormat.BlockAlignment; bufferSize = 8 * waveFormat.AverageBytesPerSecond; // Setup the secondary buffer SoundBufferDescription desc2 = new SoundBufferDescription(); desc2.Flags = BufferFlags.GlobalFocus | BufferFlags.ControlPositionNotify | BufferFlags.GetCurrentPosition2; desc2.SizeInBytes = bufferSize; desc2.Format = waveFormat; buffer = new SecondarySoundBuffer(ds, desc2); var list = new List<NotificationPosition>(); int numberOfPositions = 32; // Set notification for buffer percentiles for (int i = 0; i < numberOfPositions; i++) { list.Add(new NotificationPosition() { Event = new AutoResetEvent(false), Offset = i * bufferSize / numberOfPositions + 1, }); } // Set notification for end of buffer list.Add(new NotificationPosition() { Offset = bufferSize - 1, Event = new AutoResetEvent(false) }); firstHalfBufferIndex = numberOfPositions / 2; secondHalfBufferIndex = numberOfPositions; notifications = list.ToArray(); System.Diagnostics.Debug.Assert(notifications[firstHalfBufferIndex].Offset == bufferSize / 2 + 1); System.Diagnostics.Debug.Assert(notifications[secondHalfBufferIndex].Offset == bufferSize - 1); // Make a copy of the wait handles waitHandles = new WaitHandle[notifications.Length]; for (int i = 0; i < notifications.Length; i++) waitHandles[i] = notifications[i].Event; // Store all notification positions buffer.SetNotificationPositions(notifications); }
private static string _PlayWavFile(string fileName, double duration) { try { Initialise(); WaveStream waveFile = new WaveStream(fileName); SoundBufferDescription soundBufferDescription = new SoundBufferDescription(); soundBufferDescription.Format = waveFile.Format; soundBufferDescription.Flags = BufferFlags.Defer | BufferFlags.ControlVolume | BufferFlags.ControlPan; soundBufferDescription.SizeInBytes = (int)waveFile.Length; SecondarySoundBuffer secondarySoundBuffer = new SecondarySoundBuffer(directSound, soundBufferDescription); secondarySoundBuffer.Pan = pan; secondarySoundBuffer.Volume = volume; byte[] rawsamples = new byte[soundBufferDescription.SizeInBytes]; waveFile.Read(rawsamples, 0, soundBufferDescription.SizeInBytes); waveFile.Close(); secondarySoundBuffer.Write(rawsamples, 0, LockFlags.EntireBuffer); string name = NextName(); Buffer buffer = new Buffer(name, secondarySoundBuffer, 0, duration); buffers.Add(buffer); Thread thread = new Thread(new ParameterizedThreadStart(DoPlay)); thread.Start(buffer); if (!bAsync) thread.Join(); return name; } catch (Exception ex) { Utilities.OnError(Utilities.GetCurrentMethod(), ex); return ""; } }
private static string _PlayDX7(Primitive channels) { try { Initialise(); 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 | BufferFlags.ControlVolume | BufferFlags.ControlPan; soundBufferDescription.SizeInBytes = sampleCount * waveFormat.BlockAlignment; SecondarySoundBuffer secondarySoundBuffer = new SecondarySoundBuffer(directSound, soundBufferDescription); secondarySoundBuffer.Pan = pan; secondarySoundBuffer.Volume = volume; 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); } secondarySoundBuffer.Write(rawsamples, 0, LockFlags.EntireBuffer); string name = NextName(); Buffer buffer = new Buffer(name, secondarySoundBuffer, 0, -1); buffers.Add(buffer); Thread thread = new Thread(new ParameterizedThreadStart(DoPlay)); thread.Start(buffer); if (!bAsync) thread.Join(); return name; } catch (Exception ex) { Utilities.OnError(Utilities.GetCurrentMethod(), ex); return ""; } }
void load_sound_file(ref MemoryStream sound_stream, ref WaveStream wave_stream, ref byte[] data_array, ref SoundBufferDescription buf_desc, ref SecondarySoundBuffer buf, string file, ref bool executed) { try { if ((((Form1)(form1_reference)).retrieve_resources != null) && (((Form1)(form1_reference)).retrieve_resources.EntryFileNames.Contains(file))) { sound_stream = new MemoryStream(); ((Form1)(form1_reference)).retrieve_resources.Extract(file, sound_stream); data_array = new byte[Convert.ToInt32(sound_stream.Length)]; data_array = sound_stream.ToArray(); wave = new WaveFormat(); wave.FormatTag = WaveFormatTag.Pcm; wave.BitsPerSample = (short)((data_array[35] << 8) | data_array[34]); wave.BlockAlignment = (short)((data_array[33] << 8) | data_array[32]); wave.Channels = (short)((data_array[23] << 8) | data_array[22]); wave.SamplesPerSecond = (int)((data_array[27] << 24) | (data_array[26] << 16) | (data_array[25] << 8) | (data_array[24])); wave.AverageBytesPerSecond = (int)((data_array[27] << 24) | (data_array[26] << 16) | (data_array[25] << 8) | (data_array[24])); sound_stream = new MemoryStream(data_array); wave_stream = new WaveStream(sound_stream); buf_desc = new SoundBufferDescription(); buf_desc.Flags = BufferFlags.GlobalFocus; buf_desc.SizeInBytes = (int)sound_stream.Length; buf_desc.Format = wave; if (sound_stream.Length > 0) { buf = new SecondarySoundBuffer(device, buf_desc); wave_stream.Read(data_array, 0, buf_desc.SizeInBytes); buf.Write(data_array, 0, LockFlags.EntireBuffer); } executed = false; sound_stream.Close(); } else { buf_desc = new SoundBufferDescription(); buf_desc.Flags = BufferFlags.GlobalFocus; if (File.Exists(file)) { wave_stream = new WaveStream(file); buf_desc.Format = wave_stream.Format; buf_desc.SizeInBytes = (int)wave_stream.Length; data_array = new byte[wave_stream.Length]; buf = new SecondarySoundBuffer(device, buf_desc); wave_stream.Read(data_array, 0, buf_desc.SizeInBytes); buf.Write(data_array, 0, LockFlags.EntireBuffer); } executed = false; } } catch (DirectSoundException e) { MessageBox.Show(e.ToString(), "Error!", MessageBoxButtons.OK); } }