public static uint BufferFromOgg(string file) { using (VorbisReader vorbis = new VorbisReader(file)) { return(BufferFromOgg(vorbis)); } }
/// <summary> /// Extract the bufferdata from an ogg-file. /// </summary> /// <param name="file">The file to load the data from.</param> /// <returns>A SoundBufferData object containing the data from the specified file.</returns> public static SoundBufferData FromOgg(Stream file) { var buffers = new List <short[]>(); ALFormat format; int sampleRate; using (var vorbis = new VorbisReader(file, true)) { // Save format and samplerate for playback format = vorbis.Channels == 1 ? ALFormat.Mono16 : ALFormat.Stereo16; sampleRate = vorbis.SampleRate; var buffer = new float[16384]; int count; while ((count = vorbis.ReadSamples(buffer, 0, buffer.Length)) > 0) { // Sample value range is -0.99999994f to 0.99999994f // Samples are interleaved (chan0, chan1, chan0, chan1, etc.) // Use the OggStreamer method to cast to the right format var castBuffer = new short[count]; SoundBufferData.CastBuffer(buffer, castBuffer, count); buffers.Add(castBuffer); } } return(new SoundBufferData(buffers, format, sampleRate)); }
public static void LoadOgg(Stream file, out byte[] data, out ALFormat format, out uint sampleRate, out TimeSpan len) { using (VorbisReader vorbis = new VorbisReader(file, false)) { LoadOgg(vorbis, out data, out format, out sampleRate, out len); } }
public ConvertOGG() { DirectoryInfo dInfo = new DirectoryInfo(@"C:\Games\Thief2\FMs\DCE_v1\snd\ogg"); FileInfo[] oggFiles = dInfo.GetFiles("*.ogg", SearchOption.TopDirectoryOnly); for (int i = 0; i < oggFiles.Length; i++) { //to do - figure out how to do this. VorbisReader vR = new VorbisReader(oggFiles[i].FullName); long samples = vR.TotalSamples; float[] f = new float[samples]; vR.ReadSamples(f, 0, f.Length); byte[] sndByte = new byte[f.Length]; for (int j = 0; j < f.Length; j++) { float fl = f[j]; sndByte[j] = (byte)fl; } WaveFormat wFormat = new WaveFormat(); string wName = oggFiles[i].FullName.Replace(oggFiles[i].Extension, ".wav"); WaveFileWriter writer = new WaveFileWriter(wName, wFormat); writer.Write(sndByte, 0, sndByte.Length); } }
internal unsafe AudioClip(IResource resource) { Al.GenBuffer(out Buffer); using var reader = new VorbisReader(resource.OpenStream()); var channels = reader.Channels; var sampleRate = reader.SampleRate; var seconds = reader.TotalTime.TotalSeconds; var samples = (int)Math.Ceiling(seconds * sampleRate * channels); var floats = new Span <float>(new float[samples]); if (reader.ReadSamples(floats) <= 0) { throw new Exception("Failed to read OGG stream."); } var shorts = new Span <short>(new short[samples]); // 16 bit for (var i = 0; i < floats.Length; i++) shorts[i] = (short)(short.MaxValue * floats[i]); fixed(void *p = &shorts.GetPinnableReference()) { Al.BufferData(Buffer, channels == 2 ? Al.FormatStereo16 : Al.FormatMono16, p, shorts.Length * sizeof(short), sampleRate); } }
public override void FixHeader(TemporaryTrack track) { using (var stream = new MemoryStream(track.RawPortion)) using (var reader = new VorbisReader(stream)) { int loopStart = 0; int loopEnd = 0; var tags = reader.Tags; TryGettingVariable(tags, "LOOPSTART", ref loopStart); TryGettingVariable(tags, "LOOPEND", ref loopEnd); var headerSize = 0; var newExtraDataSize = track.OriginalEntry.NoStreamHeaderExtraDataSize + headerSize; var streamSize = track.RawPortion.Length - headerSize; var headerBytes = track.HeaderPortion; WriteByte(headerBytes, 0x04, (byte)reader.Channels); WriteUint(headerBytes, 0x08, (uint)reader.SampleRate); WriteUint(headerBytes, 0x0c, (uint)loopStart); WriteUint(headerBytes, 0x10, (uint)loopEnd); WriteUint(headerBytes, 0x14, (uint)newExtraDataSize); WriteUint(headerBytes, 0x18, (uint)streamSize); } }
void construct(Stream audio, Stream labels, bool close) { if (labels != null) { using (var read = new StreamReader(labels, Encoding.UTF8, true, 1024, !close)) this.labels = read.IterLines().Select(l => l.Split()).Where(s => s.Length == 3).Select(s => new Label(double.Parse(s[0]), double.Parse(s[1]), s[2] == "oneshot")).ToArray(); } aread = new VorbisReader(audio, close); AudioChannels channels; switch (aread.Channels) { case 1: channels = AudioChannels.Mono; break; case 2: channels = AudioChannels.Stereo; break; default: throw new InvalidDataException($"Unsupported channel count {aread.Channels} (must be mono or stereo)."); } if (this.labels?.Length > 0) { aread.DecodedTime = TimeSpan.FromSeconds(this.labels[0].Start); } samps = new float[aread.Channels * aread.SampleRate / 64]; sfx = new DynamicSoundEffectInstance(aread.SampleRate, channels); sfx.BufferNeeded += update; readthread = new Thread(readthreadfun); readthread.Start(); }
// This is used to load audio files that supported by NVorbis like ogg public static AudioClip LoadOggAudioFile(string path) { float[] audioData = null; int channels = 0; int sampleRate = 0; try { using (VorbisReader reader = new VorbisReader(path)) { //Note: Same here if (reader.TotalSamples * reader.Channels > 0x7FFFFFFFL) { return(null); } float[] data = new float[reader.TotalSamples * reader.Channels]; reader.ReadSamples(data, 0, (int)(reader.TotalSamples * reader.Channels)); channels = reader.Channels; sampleRate = reader.SampleRate; audioData = data; } } catch { return(null); } if (audioData == null) { return(null); } AudioDataHost dataHost = new AudioDataHost(audioData, channels); AudioClip clip = AudioClip.Create(path, audioData.Length / channels, channels, sampleRate, true, dataHost.PCMReaderCallback, dataHost.PCMSetPositionCallback); return(clip); }
public int GetVersionFromExportedTrackFile(string path) { if (path.EndsWith(".ogg")) { using (var vorbisReader = new VorbisReader(path)) { foreach (var comment in vorbisReader.Comments) { if (!comment.StartsWith("VERSION=", true, null)) { continue; } var value = comment.Split('=')[1]; var version = int.Parse(value); return(version); } } } else if (path.EndsWith(".flac")) { using (var flacFile = new FlacFile(path)) { if (flacFile.VorbisComment.ContainsField("VERSION")) { return(int.Parse(flacFile.VorbisComment["VERSION"].Value)); } } } throw new SoundtrackException("No version comment in specified file."); }
private void OnFinishLoading() { if (bytes != null) { if (audioSource == null) { audioSource = base.gameObject.AddComponent <AudioSource>(); } if (audioController == null) { audioController = AudioController.Instance; } vorbisReader = new VorbisReader(new MemoryStream(bytes), closeStreamOnDispose: true); if (audioClip == null) { audioClip = AudioClip.Create("Audio Clip", 1000, vorbisReader.Channels, vorbisReader.SampleRate, _3D: false, stream: true); } audioSource.clip = audioClip; audioSource.loop = isLoop; audioSource.priority = audioController.GetPriorityByType(audioType); volume = audioController.GetVolumeByType(audioType) * subVolume; audioSource.Play(); isLoop = audioSource.loop; pages = vorbisReader.Stats[0].TotalPages; isReady = true; if (onFinishLoad != null) { onFinishLoad(); } onFinishLoad = null; } }
public static uint BufferFromOgg(Stream file) { using (VorbisReader vorbis = new VorbisReader(file, false)) { return(BufferFromOgg(vorbis)); } }
public VorbisWaveReader(Stream sourceStream) { _reader = new VorbisReader(sourceStream, false); _waveFormat = WaveFormat.CreateIeeeFloatWaveFormat(_reader.SampleRate, _reader.Channels); }
private static void LoadOgg(VorbisReader vorbis, out byte[] data, out ALFormat format, out uint sampleRate, out TimeSpan len) { sampleRate = (uint)vorbis.SampleRate; format = vorbis.Channels == 1 ? ALFormat.Mono16 : ALFormat.Stereo16; len = vorbis.TotalTime; float[] buffer = new float[vorbis.SampleRate / 10 * vorbis.Channels]; List <byte> bytes = new List <byte>((int)(vorbis.SampleRate * vorbis.Channels * 2 * len.TotalSeconds)); int count = 0; while ((count = vorbis.ReadSamples(buffer, 0, buffer.Length)) > 0) { for (int i = 0; i < count; i++) { int temp = (int)(short.MaxValue * buffer [i]); if (temp > short.MaxValue) { temp = short.MaxValue; } else if (temp < short.MinValue) { temp = short.MinValue; } short tempBytes = (short)temp; byte byte1 = (byte)((tempBytes >> 8) & 255); byte byte2 = (byte)((tempBytes >> 0) & 255); // Little endian bytes.Add(byte2); bytes.Add(byte1); } } // TODO: Add better implementation so that there's no need for array copying data = bytes.ToArray(); }
public Sound(AssetData data) { using (VorbisReader reader = new VorbisReader(data.InputStream, true)) { Duration = reader.TotalTime.TotalSeconds; } }
public override bool load() { float[] readSampleBuffer = new float[AudioBuffer.MAX_BUFFER_SIZE]; short[] convBuffer = new short[AudioBuffer.MAX_BUFFER_SIZE]; myState = SourceState.LOADING; using (myReader = new VorbisReader(myFilename)) { myNumChannels = myReader.Channels; mySampleRate = myReader.SampleRate; long sampleCount = myReader.TotalSamples * myNumChannels; int numBuffers = (int)Math.Ceiling((double)sampleCount / (double)AudioBuffer.MAX_BUFFER_SIZE); for (int i = 0; i < numBuffers; i++) { AudioBuffer buffer = new AudioBuffer(myNumChannels == 1 ? AudioBuffer.AudioFormat.MONO16 : AudioBuffer.AudioFormat.STEREO16, mySampleRate); int samplesRead = myReader.ReadSamples(readSampleBuffer, 0, AudioBuffer.MAX_BUFFER_SIZE); buffer.size = samplesRead; castBuffer(readSampleBuffer, buffer.data, samplesRead); //put it in the audio system buffer.buffer(); myBuffers.Add(buffer); } myState = Source.SourceState.LOADED; Debug.print("Loaded audio file: {0}", myFilename); } return(true); }
public NVorbisSource(String path) { _vorbisReader = new VorbisReader(path); WaveFormat = new WaveFormat(_vorbisReader.SampleRate, 16, _vorbisReader.Channels, AudioEncoding.Vorbis1); posAnt = TimeSpan.Zero; _vorbisReader.SamplePosition = 0; }
public static SoundStats <float> LoadNVorbisData(string fileName) { var result = new SoundStats <float>(); var reader = new VorbisReader(fileName); result.SampleRate = reader.SampleRate; result.TotalSeconds = (float)reader.TotalTime.TotalSeconds; result.Channels = reader.Channels; var dataResult = new List <float>(); float[] buffer = new float[reader.Channels * reader.SampleRate]; // 200ms while (reader.ReadSamples(buffer, 0, buffer.Length) > 0) { dataResult.AddRange(buffer); } switch (reader.Channels) { case 1: result.Format = AudioFormat.Mono32Float; break; case 2: result.Format = AudioFormat.StereoFloat32; break; } result.BufferData = dataResult.ToArray(); return(result); }
public static void LoadOggInfo(string filePath, out long sampleRate, out long totalSamples) { if (string.IsNullOrEmpty(filePath)) { sampleRate = 0; totalSamples = 0; return; } try { using (var vorbis = new VorbisReader(filePath)) { sampleRate = vorbis.SampleRate; totalSamples = vorbis.TotalSamples; } } catch (FileNotFoundException) { throw new InvalidOperationException("Invalid .ogg file"); } catch (ArgumentException) { throw new InvalidOperationException("Invalid .ogg file"); } }
public VorbisWaveReader(string fileName) { _reader = new VorbisReader(fileName); _waveFormat = WaveFormat.CreateIeeeFloatWaveFormat(_reader.SampleRate, _reader.Channels); }
public override AudioClip Load(Identifier name, Uri uri) { using var reader = new VorbisReader(uri.LocalPath) { ClipSamples = true }; var channels = reader.Channels; var format = channels == 1 ? ALFormat.Mono16 : ALFormat.Stereo16; var sampleRate = reader.SampleRate; // TODO use stream-able clip for large sounds var totalTime = reader.TotalTime; var buffer = new float[channels * sampleRate * (int)System.Math.Ceiling(totalTime.TotalSeconds)]; var count = 0; int read; do { read = reader.ReadSamples(buffer, count, buffer.Length - count); count += read; } while (read > 0); var audioClip = new AudioClip(format, sampleRate); var data = Convert(buffer); audioClip.SetData(data); return(audioClip); }
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; } }
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); }
private SoundEffect LoadSound(Stream stream, int length, string extension) { switch (extension) { case ".wav": if (!stream.CanSeek) { stream = new MemoryStream(stream.ReadBytes(length)); } return(SoundEffect.FromStream(stream)); case ".mp3": using (var mp3Stream = new MP3Stream(stream)) using (var ms = new MemoryStream()) { mp3Stream.CopyTo(ms); return(new SoundEffect(ms.ToArray(), mp3Stream.Frequency, (AudioChannels)mp3Stream.ChannelCount)); } case ".ogg": using (var reader = new VorbisReader(stream, true)) { var buffer = new byte[reader.TotalSamples * 2 * reader.Channels]; var floatBuf = new float[buffer.Length / 2]; reader.ReadSamples(floatBuf, 0, floatBuf.Length); MusicStreamingOGG.Convert(floatBuf, buffer); return(new SoundEffect(buffer, reader.SampleRate, (AudioChannels)reader.Channels)); } } throw new ResourceLoadException("Unknown sound extension " + extension); }
public void OggDurationTest() { using (var vorbis = new VorbisReader(AudioFiles.OggFilename)) { Assert.True(vorbis.TotalTime.TotalMilliseconds > 0); } }
public new void Dispose() { if (myReader != null) { myReader.Dispose(); myReader = null; } }
VorbisAudioStream(VorbisReader reader) { if (reader == null) { throw new ArgumentNullException("reader"); } this.reader = reader; }
public override void Stop(AudioStopOptions options) { base.Stop(options); reader.Dispose(); reader = null; floatBuf = null; }
public static Song FromOggStream(Stream stream) { var reader = new VorbisReader(stream, true); var vorbisToPCMStream = new VorbisStream(reader); return(new Song(vorbisToPCMStream, reader.Channels, reader.SampleRate)); }
public override void ChangeStream(Stream stream) { this.reader.Dispose(); this.stream.Dispose(); this.stream = stream; this.reader = new VorbisReader(stream, false); }
public AudioSource(VorbisReader stream) { _stream = stream; SamplesPerBuffer = (stream.SampleRate * stream.Channels) / 3; _stream_buffer = new float[SamplesPerBuffer]; Buffer = new short[SamplesPerBuffer]; _duration = stream.TotalTime.TotalSeconds; }