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; }
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); }
private void WriteNextData(short[] data, int timems) { _soundBuffer.Write(data, _bfpos, LockFlags.None); lock (timestamp) { timestamp.Enqueue(new KeyValuePair <int, int>(_bfpos / _buffersize, timems)); } _samplesPlayed += data.Length; _bfpos += 2 * data.Length; _bfpos %= _buffDescription.BufferBytes; }
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()); }
public void WriteSamples(short[] samples, int sampleOffset, int sampleCount) { // For lack of a better place, this function will be the one that attempts to restart playing // after a sound buffer is lost. if (IsPlaying) { if (sampleCount == 0) { return; } try { _deviceBuffer.Write(samples, sampleOffset * _sound.ChannelCount, sampleCount * _sound.ChannelCount, _actualWriteOffsetBytes, LockFlags.None); _actualWriteOffsetBytes = (_actualWriteOffsetBytes + (sampleCount * _sound.BlockAlign)) % BufferSizeBytes; _filledBufferSizeBytes += sampleCount * _sound.BlockAlign; } catch (DirectSoundException) { _deviceBuffer.Restore(); StartPlaying(); } } else { if (_deviceBuffer != null) { _deviceBuffer.Restore(); } StartPlaying(); } }
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); }
protected void WriteSamples(short[] samples, int count) { if (count == 0) { return; } HasAudio = true; if (_secondaryBuffer.Status == (int)BufferStatus.BufferLost) { _secondaryBuffer.Restore(); } //If synchronise wait until there is enough free space if (_synchronizationStrategy != null && _synchronizationStrategy.SyncToAudio) { Synchronize(count); } int samplesNeeded = GetSamplesNeeded(); if (samplesNeeded < 1) { return; } if (count > samplesNeeded) { count = samplesNeeded; } _secondaryBuffer.Write(samples, 0, count, _nextWrite, LockFlags.None); IncrementWritePosition(count * sizeof(short)); }
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; })); }
private void FillAudioBuffer(bool first) { try { lock (locker_a) { int samples = Math.Max(Math.Min((int)(TotalSamples - CurrentSample), samplesPerHalfBuff), 0); if (samples < samplesPerHalfBuff) { //Дошли до конца, пустоту заполняем тишиной for (int i = samples * bytesPerSample; i < ABuffer.Length; i++) { ABuffer[i] = 0; } LastSamples = samples; } if (samples > 0) { reader.Clip.ReadAudio(h.AddrOfPinnedObject(), CurrentSample, samples); } if (CheckBufferIsLost(first) || IsError || IsAborted) { return; } if (first || GetCurrentPosition() >= ABuffer.Length) { AudioBuffer.Write(ABuffer, 0, LockFlags.None); } else { AudioBuffer.Write(ABuffer, ABuffer.Length, LockFlags.None); } CurrentSample += samples; } } catch (Exception ex) { SetError(ex); } }
public void WriteSamples(short[] samples, int sampleCount) { if (sampleCount == 0) { return; } _deviceBuffer.Write(samples, 0, sampleCount * Sound.ChannelCount, _actualWriteOffsetBytes, LockFlags.None); _actualWriteOffsetBytes = (_actualWriteOffsetBytes + (sampleCount * Sound.BlockAlign)) % BufferSizeBytes; _filledBufferSizeBytes += sampleCount * Sound.BlockAlign; }
public void flush() { if (audioBuffer != null) { audioBuffer.Stop(); audioBuffer.CurrentPosition = 0; audioBuffer.Write(silence, 0, LockFlags.None); } offsetBytes = 0; prevPlayPos = 0; ptsPos = 0; prevPtsPos = 0; playLoops = 0; ptsLoops = 0; audioState = AudioState.START_PLAY_AFTER_NEXT_WRITE; }
private void PushTempBlock() { // If we haven't recieved a schedule, we don't know where to place this on the play buffer. // Give up! if (!this.scheduleAccepted) { return; } const int TEMP_COPY_SIZE = TEMP_BUFFER_SIZE * sizeof(uint); // Check to see if we're about to write over the play buffer (an unforgiveable offense!!) int playPosition = this.playBuffer.CurrentPlayPosition; int checkPositionMin = this.AddToPosition(this.currentWritePosition, -this.play_copy_guess_offset); int checkPositionMax = this.AddToPosition(this.currentWritePosition, TEMP_COPY_SIZE); bool aboutToWriteOverPlayPosition = this.GetRealPositionInclusive(checkPositionMin, checkPositionMax, playPosition); if (aboutToWriteOverPlayPosition) { // WOAH! Don't write over the play buffer! That would suck! // The system must be running slowly. Send the write buffer way back behind the play buffer. if (FourDO.Utilities.Globals.RunOptions.LogAudioDebug) { Trace.WriteLine(LOG_PREFIX + "Resetting:About to write over play buffer"); } this.ResetWritePosition(); } ////////////////////// // Copy it wherever the current position is if (this.currentWritePosition + TEMP_COPY_SIZE > bufferDescription.SizeInBytes) { int firstWriteSize = (bufferDescription.SizeInBytes - this.currentWritePosition); playBuffer.Write <uint>(tempBuffer, 0, firstWriteSize / sizeof(uint), bufferDescription.SizeInBytes - firstWriteSize, LockFlags.None); playBuffer.Write <uint>(tempBuffer, firstWriteSize / sizeof(uint), (TEMP_COPY_SIZE - firstWriteSize) / sizeof(uint), 0, LockFlags.None); } else { playBuffer.Write <uint>(this.tempBuffer, this.currentWritePosition, LockFlags.None); } this.currentWritePosition += TEMP_COPY_SIZE; this.currentWritePosition = this.currentWritePosition % bufferDescription.SizeInBytes; }
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(""); } }
/// <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 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); }
//--------------------// #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); }
public void SetupSoundBuffer(DirectSound device) { if (SecondaryBuffer != null) { throw new InvalidOperationException(string.Format("Already exists SoundBuffer.")); } SecondaryBuffer = new SecondarySoundBuffer(device, SoundBufferDesc); SecondaryBuffer.Write(RawAudioStream, 0, LockFlags.EntireBuffer); SecondaryBuffer.CurrentPlayPosition = 0; SecondaryBuffer.Volume = MinimumVolume; MinimumFrequency = device.Capabilities.MinSecondarySampleRate; MaximumFrequency = device.Capabilities.MaxSecondarySampleRate; DefaultFrequency = SoundBufferDesc.Format.SamplesPerSecond; }
/// <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 SubmitBuffer(ref byte[] samplesBuffer) { if (!canRender) { return; } if (IsRendering) { return; } if (buffer == null) { return; } IsRendering = true; buffer.Write(samplesBuffer, 0, LockFlags.None); IsRendering = false; }
public static SecondarySoundBuffer LoadSound(string FileName) { if (isFromResource) { FileName = FileName.Split('.')[0]; } if (!File.Exists(FileName)) { throw (new ArgumentException("The sound " + FileName + " could not be found.")); } SoundBufferDescription BufferDesc = new SoundBufferDescription(); //enable volume changes on all buffers created with this function. BufferDesc.Flags = SharpDX.DirectSound.BufferFlags.ControlVolume | SharpDX.DirectSound.BufferFlags.ControlFrequency //| SharpDX.DirectSound.BufferFlags.StickyFocus | SharpDX.DirectSound.BufferFlags.ControlPan; //load wave file into DirectSound buffer 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(); } return(theBuffer); }
/// <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); }
/// <summary> /// Load sound data. wavData must not contain WAV Head. /// </summary> /// <param name="wavBytes"></param> /// <returns>Returns duration.</returns> public decimal Load(byte[] wavBytes, int sampleRate, int bitsPerSample, int channelCount) { var format = new SharpDX.Multimedia.WaveFormat(sampleRate, bitsPerSample, channelCount); // Create and set the buffer description. var desc = new SoundBufferDescription(); desc.Format = format; desc.Flags = // Play sound even if application loses focus. BufferFlags.GlobalFocus | // This has to be true to use effects. BufferFlags.ControlEffects; desc.BufferBytes = wavBytes.Length; // Create and set the buffer for playing the sound. ApplicationBuffer = new SecondarySoundBuffer(ApplicationDevice, desc); ApplicationBuffer.Write(wavBytes, 0, LockFlags.None); var duration = AudioHelper.GetDuration(wavBytes.Length, sampleRate, bitsPerSample, channelCount); return(duration); }
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 static SecondarySoundBuffer CreateSoundBufferFromOgg(string Filename) { // Load ogg file using (OggVorbisFileStream oggStream = new OggVorbisFileStream(Filename)) { using (MemoryStream memStream = new MemoryStream()) { byte[] tempData = new byte[512]; int bytesReturned = -1; int bytesRead = 0; while (bytesReturned != 0) { bytesReturned = oggStream.Read(tempData, 0, tempData.Length); memStream.Write(tempData, 0, bytesReturned); bytesRead += bytesReturned; } WaveFormat 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 = (int)memStream.Length; description.Flags = BufferFlags.ControlVolume | BufferFlags.GlobalFocus; // Create the buffer. SecondarySoundBuffer buffer = new SecondarySoundBuffer(device, description); byte[] data = memStream.ToArray(); buffer.Write(data, 0, LockFlags.None); return(buffer); } } }
private SecondarySoundBuffer loadSoundFile(String filename) { SecondarySoundBuffer sndBuffer = null; using (WaveStream wavFile = new WaveStream(Application.StartupPath + "\\Resources\\" + filename)) { SoundBufferDescription sndBufferDesc; sndBufferDesc = new SoundBufferDescription(); sndBufferDesc.SizeInBytes = (int)wavFile.Length; sndBufferDesc.Flags = SlimDX.DirectSound.BufferFlags.ControlVolume; sndBufferDesc.Format = wavFile.Format; sndBuffer = new SecondarySoundBuffer(directSound, sndBufferDesc); // now load the sound. byte[] wavData = new byte[sndBufferDesc.SizeInBytes]; wavFile.Read(wavData, 0, (int)wavFile.Length); sndBuffer.Write(wavData, 0, LockFlags.None); } return(sndBuffer); }
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 SecondarySoundBuffer CreateBuffer() { SecondarySoundBuffer buff; BufferFlags flags = BufferFlags.ControlVolume; if (Config.SoundInBackground) { flags |= BufferFlags.GlobalFocus; } BufferList.Add(buff = new SecondarySoundBuffer(DXSoundManager.Device, new SoundBufferDescription { Format = Format, SizeInBytes = RawData.Length, Flags = flags }) { Volume = Volume }); buff.Write(RawData, 0, LockFlags.EntireBuffer); return(buff); }
public bool Start() { lock (this) { Stop(); try { Secondary = new SecondarySoundBuffer(Device, Desc); Secondary.CurrentPlayPosition = 0; /* clear first */ Secondary.Write(new byte[Desc.SizeInBytes], 0, LockFlags.EntireBuffer); Started = true; ErrorString = null; } catch (Exception e) { RealAudioSamplingRate = 0; return(false); } } return(true); }
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 _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(""); } }
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); } }
/// <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); } }
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); } }
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 ""; } }
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 ""; } }
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 ""; } }