public override void InitializeALBuffers() { base.InitializeALBuffers(); reader ??= new VorbisReader(Filename); ALFormat = reader.Channels == 1 ? Al.FormatMono16 : Al.FormatStereo16; SampleRate = reader.SampleRate; if (!Stream) { int bufferSize = (int)reader.TotalSamples * reader.Channels; float[] floatBuffer = new float[bufferSize]; short[] shortBuffer = new short[bufferSize]; int readSamples = reader.ReadSamples(floatBuffer, 0, bufferSize); playbackAmplitude = new List <float>(); for (int i = 0; i < bufferSize; i += reader.Channels * AMPLITUDE_SAMPLE_COUNT) { float maxAmplitude = 0.0f; for (int j = i; j < i + reader.Channels * AMPLITUDE_SAMPLE_COUNT; j++) { if (j >= bufferSize) { break; } maxAmplitude = Math.Max(maxAmplitude, Math.Abs(floatBuffer[j])); } playbackAmplitude.Add(maxAmplitude); } CastBuffer(floatBuffer, shortBuffer, readSamples); Al.BufferData(ALBuffer, ALFormat, shortBuffer, readSamples * sizeof(short), SampleRate); int alError = Al.GetError(); if (alError != Al.NoError) { throw new Exception("Failed to set buffer data for non-streamed audio! " + Al.GetErrorString(alError)); } MuffleBuffer(floatBuffer, SampleRate, reader.Channels); CastBuffer(floatBuffer, shortBuffer, readSamples); Al.BufferData(ALMuffledBuffer, ALFormat, shortBuffer, readSamples * sizeof(short), SampleRate); alError = Al.GetError(); if (alError != Al.NoError) { throw new Exception("Failed to set buffer data for non-streamed audio! " + Al.GetErrorString(alError)); } reader.Dispose(); reader = null; } }
private void Cerrar() { if (_vorbisReader != null) { _vorbisReader.Dispose(); } }
static void PlayOGG(string filename) { var buffers = Initialize(out IntPtr device, out ContextHandle context, out int source); var vorbis = new VorbisReader(string.Format(AudioFilesPathFormat, filename)); var stream = new MemoryStream(); var samples = new float[vorbis.Channels * vorbis.SampleRate]; var samplesRead = 0; while ((samplesRead = vorbis.ReadSamples(samples, 0, samples.Length)) > 0) { var readBuffer = new byte[samplesRead * 4]; Buffer.BlockCopy(samples, 0, readBuffer, 0, readBuffer.Length); stream.Write(readBuffer, 0, readBuffer.Length); } stream.Position = 0; PlayAndDispose(stream, buffers, source, vorbis.SampleRate); vorbis.Dispose(); vorbis = null; Dispose(ref device, ref context); }
public void Close() { if (mReader != null) { mReader.Dispose(); mReader = null; } }
public override void Stop(AudioStopOptions options) { base.Stop(options); reader.Dispose(); reader = null; floatBuf = null; }
/// <summary> /// Dispose /// </summary> public void Dispose() { if (reader != null) { reader.Dispose(); reader = null; } }
public new void Dispose() { if (myReader != null) { myReader.Dispose(); myReader = null; } }
public override void Dispose() { if (Stream) { reader.Dispose(); } base.Dispose(); }
public void Dispose() { Stop(); if (_reader != null) { _reader.Dispose(); } AL.DeleteSource(_source); }
protected override void Dispose(bool disposing) { if (disposing && _reader != null) { _reader.Dispose(); _reader = null; } base.Dispose(disposing); }
public void Dispose() { if (!_disposed) { _vorbisReader.Dispose(); } else { throw new ObjectDisposedException("NVorbisSource"); } _disposed = true; }
protected override void Dispose(bool disposing) { if (!_ogg_disposed) { if (disposing) { m_reader.Dispose(); } _ogg_disposed = true; base.Dispose(disposing); } }
/// <summary> /// Dispose of the stream. /// </summary> public void Dispose() { //Dispose of stream if haven't already. if (!_disposed) { _vorbisReader.Dispose(); } //Object has already been disposed. //else //throw new ObjectDisposedException("NVorbisSource"); //Set disposed to true. _disposed = true; }
public OggSound(SoundManager owner, string filename, bool stream) : base(owner, filename, stream, true) { if (!ToolBox.IsProperFilenameCase(filename)) { DebugConsole.ThrowError("Sound file \"" + filename + "\" has incorrect case!"); } reader = new VorbisReader(filename); ALFormat = reader.Channels == 1 ? ALFormat.Mono16 : ALFormat.Stereo16; SampleRate = reader.SampleRate; if (!stream) { int bufferSize = (int)reader.TotalSamples * reader.Channels; float[] floatBuffer = new float[bufferSize]; short[] shortBuffer = new short[bufferSize]; int readSamples = reader.ReadSamples(floatBuffer, 0, bufferSize); CastBuffer(floatBuffer, shortBuffer, readSamples); AL.BufferData((int)ALBuffer, ALFormat, shortBuffer, readSamples * sizeof(short), SampleRate); ALError alError = AL.GetError(); if (alError != ALError.NoError) { throw new Exception("Failed to set buffer data for non-streamed audio! " + AL.GetErrorString(alError)); } MuffleBuffer(floatBuffer, SampleRate, reader.Channels); CastBuffer(floatBuffer, shortBuffer, readSamples); AL.BufferData((int)ALMuffledBuffer, ALFormat, shortBuffer, readSamples * sizeof(short), SampleRate); alError = AL.GetError(); if (alError != ALError.NoError) { throw new Exception("Failed to set buffer data for non-streamed audio! " + AL.GetErrorString(alError)); } reader.Dispose(); } }
public void Dispose() { aread?.Dispose(); sfx?.Dispose(); aread = null; sfx = null; labels = null; samps = null; buf = null; disposed = true; data = null; bufUsed.Set(); readthread.Join(); bufSent?.Dispose(); bufUsed?.Dispose(); }
public void StopAudio() { if (loadThread != null && loadThread.IsAlive) { loadThread.Abort(); } isReady = false; isLoading = false; isLoaded = false; if (audioSource != null) { audioSource.Stop(); } if (vorbisReader != null) { vorbisReader.Dispose(); } vorbisReader = null; bytes = null; iTween.Stop(base.gameObject); }
public ISoundData Decode(Stream stream) { VorbisReader reader = null; try { reader = new VorbisReader(stream, false); int channels = reader.Channels; const int BITS_PER_SAMPLE = 16; int sampleRate = reader.SampleRate; //Code from: https://github.com/AdamsLair/duality/blob/a911c46b6bc830c05d3bb1202f8e7060543eaefa/Duality/Audio/OggVorbis.cs List <float[]> allBuffers = new List <float[]>(); bool eof = false; int totalSamplesRead = 0; int dataRead = 0; while (!eof) { float[] buffer = new float[DEFAULT_BUFFER_SIZE]; int bufferSamplesRead = 0; while (bufferSamplesRead < buffer.Length) { int samplesRead; lock (_readMutex) { samplesRead = reader.ReadSamples(buffer, dataRead, buffer.Length - dataRead); } if (samplesRead > 0) { bufferSamplesRead += samplesRead; } else { eof = true; break; } } allBuffers.Add(buffer); totalSamplesRead += bufferSamplesRead; } if (totalSamplesRead > 0) { short[] data = new short[totalSamplesRead]; int offset = 0; for (int i = 0; i < allBuffers.Count; i++) { int len = Math.Min(totalSamplesRead - offset, allBuffers[i].Length); castBuffer(allBuffers[i], data, offset, len); offset += len; } return(new SoundData(channels, BITS_PER_SAMPLE, sampleRate, data, Marshal.SizeOf <short>() * data.Length)); } else { Debug.WriteLine("OggDecoder: No samples found in ogg file"); return(null); } } catch (InvalidDataException e) { Debug.WriteLine("OggDecoder: Failed to read ogg. " + e.ToString()); return(null); } finally { if (reader != null) { reader.Dispose(); } } }
private void process(int playPointer, bool loop) { bool noMoreData = false; VorbisReader vorbis = new VorbisReader(fileNames[playPointer]); if (fileNames.Length > 1) { if (playPointer < fileNames.Length - 1) { loop = false; } else { loop = true; } } float[] outBuffer = new float[vorbis.Channels * vorbis.SampleRate / 5]; // If this is a consecutive track, we've already initialized the sourceVoice so we don't need to do it again. // We can just fill the already-playing voice with data from the new track. if (playPointer == 0) { WaveFormat waveFormat = new WaveFormat(vorbis.SampleRate, bitsPerSample, vorbis.Channels); sourceVoice = new SourceVoice(device, waveFormat, false); } const int rescaleFactor = 32767; Func <int, List <DataStream> > getAtLeast = howMany => { List <DataStream> samples = new List <DataStream>(); if (noMoreData) { return(samples); } int PcmBytes = 0; int howManySoFar = 0; while ((PcmBytes = vorbis.ReadSamples(outBuffer, 0, outBuffer.Length)) > 0) { short[] intData = new short[PcmBytes]; byte[] data = new byte[PcmBytes * 2]; for (int index = 0; index < PcmBytes; index++) { intData[index] = (short)(outBuffer[index] * rescaleFactor); byte[] b = BitConverter.GetBytes(intData[index]); b.CopyTo(data, index * 2); } samples.Add(DataStream.Create <byte>(data, true, false)); if (++howManySoFar == howMany) { break; } } if (howManySoFar < howMany) { noMoreData = true; } return(samples); }; Func <List <DataStream>, List <AudioBuffer> > convertToAudioBuffers = dataStreams => { List <AudioBuffer> audioBuffers = new List <AudioBuffer>(); foreach (DataStream s in dataStreams) { audioBuffers.Add(new AudioBuffer { Stream = s, Flags = BufferFlags.None, AudioBytes = (int)s.Length }); } return(audioBuffers); }; Action <List <AudioBuffer> > submitToSourceVoice = (audioBuffers) => { foreach (AudioBuffer a in audioBuffers) { sourceVoice.SubmitSourceBuffer(a, null); } }; new Thread(() => { VoiceState state; List <DataStream> streams = getAtLeast(minimumNumberOfBuffers); List <AudioBuffer> buffers = convertToAudioBuffers(streams); memories.AddRange(buffers); submitToSourceVoice(buffers); // If this isn't the first consecutive track, we've already started playing this sourceVoice and are just filling it with data from the new track. if (playPointer == 0) { sourceVoice.Start(); } started = true; while (true) { if (stopNow) { break; } state = sourceVoice.State; if (state.BuffersQueued < minimumNumberOfBuffers) { // Fill the source with more samples since we're running low. List <DataStream> moreStreams = getAtLeast(minimumNumberOfBuffers); if (moreStreams.Count < minimumNumberOfBuffers && loop) { vorbis.DecodedPosition = 0; noMoreData = false; } if (state.BuffersQueued == 0 && moreStreams.Count == 0) { break; // Nothing remaining to fill the source with and we've played everything. } List <AudioBuffer> moreBuffers = convertToAudioBuffers(moreStreams); // The buffers that are already played can now be removed. for (int i = 0; i < memories.Count - state.BuffersQueued; i++) { memories[i].Stream.Close(); } memories.RemoveRange(0, memories.Count - state.BuffersQueued); memories.AddRange(moreBuffers); submitToSourceVoice(moreBuffers); } Thread.Sleep(10); } // If we're transitioning to the next track and haven't received a stop signal. if (!stopNow && playPointer < (fileNames.Length - 1)) { process(playPointer + 1, loop); vorbis.Dispose(); return; } sourceVoice.Stop(); sourceVoice.FlushSourceBuffers(); for (int i = 0; i < memories.Count; i++) { memories[i].Stream.Close(); } memories.Clear(); vorbis.Dispose(); m_status = Status.stopped; }).Start(); }
public void Dispose() { reader.Dispose(); reader = null; }
public override void Dispose() { m_reader.Dispose(); }
private static void ConvertSound(Sound sound) { if (!sound.HasStartFile && !sound.HasStartFile) { return; } FileInfo outFile = CurrentDirectory.GetDirectory("out").GetFile($"{sound.Name}.{Arguments.Format.ToString().ToLower()}"); if (!Arguments.Overwrite && outFile.Exists) { return; } FileInfo tempWave = new FileInfo(Path.GetTempFileName()); WaveReader reader = new WaveReader(); AudioData audio = null; Console.WriteLine($"Processing {sound.Name}..."); if (sound.HasStartFile && !sound.HasLoopFile) { using (VorbisWaveReader vorbisStart = new VorbisWaveReader(GameSounds.GetFile(sound.StartFileName).FullName)) { WaveFileWriter.CreateWaveFile(tempWave.FullName, vorbisStart.ToWaveProvider16()); } using (FileStream stream = tempWave.OpenRead()) { audio = reader.Read(stream); } } else if (sound.HasStartFile && sound.HasLoopFile) { VorbisWaveReader vorbisStart = new VorbisWaveReader(GameSounds.GetFile(sound.StartFileName).FullName); VorbisWaveReader vorbisLoop = new VorbisWaveReader(GameSounds.GetFile(sound.LoopFileName).FullName); if (vorbisStart.WaveFormat.SampleRate < vorbisLoop.WaveFormat.SampleRate) { MediaFoundationResampler sampeler = new MediaFoundationResampler(vorbisStart, vorbisLoop.WaveFormat.SampleRate); WaveFileWriter.CreateWaveFile(tempWave.FullName, sampeler.ToSampleProvider().FollowedBy(vorbisLoop).ToWaveProvider16()); } else if (vorbisStart.WaveFormat.SampleRate > vorbisLoop.WaveFormat.SampleRate) { MediaFoundationResampler sampeler = new MediaFoundationResampler(vorbisLoop, vorbisStart.WaveFormat.SampleRate); WaveFileWriter.CreateWaveFile(tempWave.FullName, vorbisStart.FollowedBy(sampeler.ToSampleProvider()).ToWaveProvider16()); } else { WaveFileWriter.CreateWaveFile(tempWave.FullName, vorbisStart.FollowedBy(vorbisLoop).ToWaveProvider16()); } VorbisReader dataStart = new VorbisReader(GameSounds.GetFile(sound.StartFileName).FullName); VorbisReader dataLoop = new VorbisReader(GameSounds.GetFile(sound.LoopFileName).FullName); int startLoop = (int)dataStart.TotalSamples; int endLoop = (int)dataStart.TotalSamples + (int)dataLoop.TotalSamples; vorbisStart.Dispose(); vorbisLoop.Dispose(); dataStart.Dispose(); dataLoop.Dispose(); using (FileStream stream = tempWave.OpenRead()) { audio = reader.Read(stream); } audio.SetLoop(true, startLoop, endLoop); } else if (!sound.HasStartFile && sound.HasLoopFile) { VorbisWaveReader vorbisLoop = new VorbisWaveReader(GameSounds.GetFile(sound.LoopFileName).FullName); WaveFileWriter.CreateWaveFile(tempWave.FullName, vorbisLoop.ToWaveProvider16()); VorbisReader dataLoop = new VorbisReader(GameSounds.GetFile(sound.LoopFileName).FullName); int totalSamples = (int)dataLoop.TotalSamples; vorbisLoop.Dispose(); dataLoop.Dispose(); audio = reader.Read(tempWave.OpenRead()); audio.SetLoop(true, 0, totalSamples); } if (audio != null) { BCFstmWriter writer = new BCFstmWriter(Arguments.Target); writer.Configuration.Codec = Arguments.Codec; writer.Configuration.Endianness = Arguments.Endianness; using (FileStream stream = outFile.OpenWrite()) { writer.WriteToStream(audio, stream); } } }
private void BeginOgg(bool isLooping, string volumeGroup) { if (string.IsNullOrEmpty(this.oggFilePath)) { return; } lock (this.oggQueueLock) { } this.oggPlaybackEnded = false; this.oggSource = GenSourceWithVolume(volumeGroup); var currentSource = this.oggSource; int channels, bits_per_sample; VorbisReader vorbis; try { vorbis = new VorbisReader(this.oggFilePath); } catch (ArgumentException) { throw new InvalidOperationException("Invalid .ogg file"); } // get the channels & sample rate channels = vorbis.Channels; bits_per_sample = 16; this.oggSampleRate = vorbis.SampleRate; var soundFormat = GetSoundFormat(channels, bits_per_sample); // OPTIONALLY: get a TimeSpan indicating the total length of the Vorbis stream var totalTime = vorbis.TotalTime; // create a buffer for reading samples var valuesPerBuffer = (int)(channels * oggSampleRate * OggBufferSize); // 1s/5 = 200ms var readBuffer = new float[valuesPerBuffer]; // get the initial position (obviously the start) var position = TimeSpan.Zero; this.oggTotalSamples = vorbis.TotalSamples; var sampleEnd = isLooping ? this.oggLoopEnd : this.oggTotalSamples; if (this.oggProgress < 0 || this.oggProgress >= sampleEnd) { this.OggSeek(0); } this.UpdateOggProgress(this.oggPausePosition); vorbis.SeekTo(this.oggPausePosition); var buffersInitialized = false; var buffers = new List <int>(); var playbackStopDetected = false; this.WaitOnLock(this.oggQueueLock, () => { for (int i = 0; i < OggBufferCount; i++) { var currentBuffer = AL.GenBuffer(); QueueBuffer(currentSource, currentBuffer, vorbis, soundFormat, oggSampleRate, valuesPerBuffer, sampleEnd); buffers.Add(currentBuffer); } var allBuffersProcessed = false; while (!buffersInitialized || (!playbackStopDetected && !this.oggPlaybackEnded)) { buffersInitialized = true; AL.GetSource(currentSource, ALGetSourcei.BuffersQueued, out int buffersQueued); AL.GetSource(currentSource, ALGetSourcei.BuffersProcessed, out int buffersProcessed); var newUnqueuedSize = 0; for (int i = 0; i < buffersProcessed; i++) { var currentBuffer = buffers.First(); buffers.Remove(currentBuffer); AL.GetBuffer(currentBuffer, ALGetBufferi.Size, out int currentBufferSize); newUnqueuedSize += currentBufferSize; AL.SourceUnqueueBuffers(currentSource, 1, new[] { currentBuffer }); QueueBuffer(currentSource, currentBuffer, vorbis, soundFormat, oggSampleRate, valuesPerBuffer, sampleEnd); buffers.Add(currentBuffer); } allBuffersProcessed = vorbis.SamplePosition >= this.oggTotalSamples && (!isLooping); if (allBuffersProcessed && buffersProcessed != 0) { var unqueuedBuffers = new int[buffersProcessed]; AL.SourceUnqueueBuffers(currentSource, buffersProcessed, unqueuedBuffers); foreach (var currentBuffer in unqueuedBuffers) { AL.GetBuffer(currentBuffer, ALGetBufferi.Size, out int currentBufferSize); newUnqueuedSize += currentBufferSize; } } var newProgress = newUnqueuedSize / (channels * (bits_per_sample / 8)); var adjustedProgress = this.oggProgress + newProgress; if (AL.GetSourceState(currentSource) == ALSourceState.Playing) { this.UpdateOggProgress(adjustedProgress); } else { AL.SourcePlay(currentSource); } if (isLooping) { var realLoopEnd = Math.Min(this.oggLoopEnd, this.oggTotalSamples); if (vorbis.SamplePosition >= realLoopEnd) { vorbis.SeekTo(this.oggLoopStart); } if (this.oggProgress >= realLoopEnd) { this.UpdateOggProgress(this.oggLoopStart + (this.oggProgress % realLoopEnd)); } } else { var realLoopEnd = Math.Min(this.oggLoopEnd, this.oggTotalSamples); if (vorbis.SamplePosition >= realLoopEnd) { this.oggPlaybackEnded = true; } } } vorbis.Dispose(); }); while (!buffersInitialized) { Thread.Sleep(10); } this.OggPlayback?.Invoke(this, new OggPlaybackEventArgs { StateChange = ALSourceState.Playing }); this.Play(currentSource, () => { playbackStopDetected = true; this.WaitOnLock(this.oggQueueLock, () => { foreach (var buf in buffers) { AL.DeleteBuffer(buf); } this.OggPlayback?.Invoke(this, new OggPlaybackEventArgs { StateChange = ALSourceState.Stopped }); this.oggSource = -1; }); }, true); }
protected override void FreeResources() { _reader.Dispose(); }
private const int AMPLITUDE_SAMPLE_COUNT = 4410; //100ms in a 44100hz file public OggSound(SoundManager owner, string filename, bool stream, XElement xElement) : base(owner, filename, stream, true, xElement) { filename = filename.CleanUpPath(); if (!ToolBox.IsProperFilenameCase(filename)) { DebugConsole.ThrowError("Sound file \"" + filename + "\" has incorrect case!"); } reader = new VorbisReader(filename); ALFormat = reader.Channels == 1 ? Al.FormatMono16 : Al.FormatStereo16; SampleRate = reader.SampleRate; if (!stream) { int bufferSize = (int)reader.TotalSamples * reader.Channels; float[] floatBuffer = new float[bufferSize]; short[] shortBuffer = new short[bufferSize]; int readSamples = reader.ReadSamples(floatBuffer, 0, bufferSize); playbackAmplitude = new List <float>(); for (int i = 0; i < bufferSize; i += reader.Channels * AMPLITUDE_SAMPLE_COUNT) { float maxAmplitude = 0.0f; for (int j = i; j < i + reader.Channels * AMPLITUDE_SAMPLE_COUNT; j++) { if (j >= bufferSize) { break; } maxAmplitude = Math.Max(maxAmplitude, Math.Abs(floatBuffer[j])); } playbackAmplitude.Add(maxAmplitude); } CastBuffer(floatBuffer, shortBuffer, readSamples); Al.BufferData(ALBuffer, ALFormat, shortBuffer, readSamples * sizeof(short), SampleRate); int alError = Al.GetError(); if (alError != Al.NoError) { throw new Exception("Failed to set buffer data for non-streamed audio! " + Al.GetErrorString(alError)); } MuffleBuffer(floatBuffer, SampleRate, reader.Channels); CastBuffer(floatBuffer, shortBuffer, readSamples); Al.BufferData(ALMuffledBuffer, ALFormat, shortBuffer, readSamples * sizeof(short), SampleRate); alError = Al.GetError(); if (alError != Al.NoError) { throw new Exception("Failed to set buffer data for non-streamed audio! " + Al.GetErrorString(alError)); } reader.Dispose(); } }
public void Dispose() { _vorbis?.Dispose(); }
public void Dispose() { reader.Dispose(); }
protected override void Dispose(bool disposing) { BufferAllocator.Free(floats); reader.Dispose(); base.Dispose(disposing); }
protected override void Dispose(bool isDisposing) { reader.Dispose(); base.Dispose(isDisposing); }
public void Dispose() { _stream.Dispose(); }
protected override void Dispose(bool disposing) { _reader.Dispose(); base.Dispose(disposing); }