private bool Converter(string srcPath, string dstPath) { using (var stream = AssetCooker.InputBundle.OpenFile(srcPath)) { // All sounds below 100kb size (can be changed with cooking rules) are converted // from OGG to Wav/Adpcm var rules = AssetCooker.CookingRulesMap[srcPath]; if (stream.Length > rules.ADPCMLimit * 1024) { AssetCooker.OutputBundle.ImportFile(dstPath, stream, 0, oggExtension, AssetCooker.InputBundle.GetFileLastWriteTime(srcPath), AssetAttributes.None, AssetCooker.CookingRulesMap[srcPath].SHA1); } else { Console.WriteLine("Converting sound to ADPCM/IMA4 format..."); using (var input = new OggDecoder(stream)) { using (var output = new MemoryStream()) { WaveIMA4Converter.Encode(input, output); output.Seek(0, SeekOrigin.Begin); AssetCooker.OutputBundle.ImportFile(dstPath, output, 0, oggExtension, AssetCooker.InputBundle.GetFileLastWriteTime(srcPath), AssetAttributes.None, AssetCooker.CookingRulesMap[srcPath].SHA1); } } } return(true); } }
private static void SyncSounds() { const string sourceExtension = ".ogg"; if (Platform == TargetPlatform.Unity) { SyncRawAssets(sourceExtension); return; } SyncUpdated(sourceExtension, ".sound", (srcPath, dstPath) => { using (var stream = new FileStream(srcPath, FileMode.Open)) { // All sounds below 100kb size (can be changed with cooking rules) are converted // from OGG to Wav/Adpcm var rules = cookingRulesMap[srcPath]; if (stream.Length > rules.ADPCMLimit * 1024) { AssetBundle.ImportFile(dstPath, stream, 0, sourceExtension, AssetAttributes.None, cookingRulesMap[srcPath].SHA1); } else { Console.WriteLine("Converting sound to ADPCM/IMA4 format..."); using (var input = new OggDecoder(stream)) { using (var output = new MemoryStream()) { WaveIMA4Converter.Encode(input, output); output.Seek(0, SeekOrigin.Begin); AssetBundle.ImportFile(dstPath, output, 0, sourceExtension, AssetAttributes.None, cookingRulesMap[srcPath].SHA1); } } } return(true); } }); }
private Stream DecodeToMemoryStream(OggDecoder decoder) { Stream output = new MemoryStream(4096); foreach (PCMChunk chunk in decoder) { output.Write(chunk.Bytes, 0, chunk.Length); } output.Seek(0, SeekOrigin.Begin); return(output); }
public static SoundEffect Load(string path) { SoundEffect soundEffect; using (MemoryStream stream = new MemoryStream()) using (BinaryWriter writer = new BinaryWriter(stream)) { OggDecoder decoder = new OggDecoder(); decoder.Initialize(File.OpenRead(path)); byte[] data = decoder.SelectMany(chunk => chunk.Bytes.Take(chunk.Length)).ToArray(); WriteWave(writer, decoder.Stereo ? 2 : 1, decoder.SampleRate, data); stream.Position = 0; soundEffect = SoundEffect.FromStream(stream); } return(soundEffect); }
public static SoundEffect Convert(string path) { string wavPath = path.Replace(".ogg", ".wav"); SoundEffect soundEffect = null; using (FileStream stream = new FileStream(wavPath, FileMode.Create)) using (BinaryWriter writer = new BinaryWriter(stream)) { OggDecoder decoder = new OggDecoder(); decoder.Initialize(File.OpenRead(path)); byte[] data = decoder.SelectMany(chunk => chunk.Bytes.Take(chunk.Length)).ToArray(); WriteWave(writer, decoder.Stereo ? 2 : 1, decoder.SampleRate, data); } using (FileStream stream = new FileStream(wavPath, FileMode.Open)) soundEffect = SoundEffect.FromStream(stream); return(soundEffect); }
public OggVorbisFile(string name, string filepath, Sound soundType) { Name = name; string cachefile = SystemInfo.DecodedMusicCache + SystemInfo.PathSeparator.ToString () + soundType.ToString () + "_" + name.GetHashCode ().ToString () + ".wav"; Log.BlockList (id: 33, before: " - ", after: "", begin: "Load ogg audio files:", end: ""); Log.BlockList (id: 34, before: " - ", after: "", begin: "Decode ogg audio files:", end: ""); byte[] data; try { Log.ListElement (33, "[", soundType, "] ", name); data = File.ReadAllBytes (cachefile); } catch (Exception) { Log.ListElement (34, "[", soundType, "] ", name); OggDecoder decoder = new OggDecoder (); decoder.Initialize (TitleContainer.OpenStream (filepath)); data = decoder.SelectMany (chunk => chunk.Bytes.Take (chunk.Length)).ToArray (); using (MemoryStream stream = new MemoryStream ()) using (BinaryWriter writer = new BinaryWriter (stream)) { WriteWave (writer, decoder.Stereo ? 2 : 1, decoder.SampleRate, data); stream.Position = 0; data = stream.ToArray (); } File.WriteAllBytes (cachefile, data); } using (MemoryStream stream = new MemoryStream (data)) { stream.Position = 0; SoundEffect soundEffect = SoundEffect.FromStream (stream); internalFile = new SoundEffectFile (name, soundEffect, soundType); } }
public static void CompileOggs(string path = null) { if (path == null) { path = Path.GetDirectoryName(Engine.Assembly.Location); } else if (path.StartsWith(".")) { path = (Path.GetDirectoryName(Engine.Assembly.Location) + path.Substring(1)); } if (!Directory.Exists(path)) { return; } var files = Engine.DirSearch(path, ".ogg"); foreach (var file in files) { var directoryName = Path.GetDirectoryName(file); var newFile = (directoryName + "\\" + Path.GetFileNameWithoutExtension(file) + ".wav"); if (File.Exists(newFile)) { continue; } using (var fs = new FileStream(newFile, FileMode.CreateNew)) { var decoder = new OggDecoder(); decoder.Initialize(new FileStream(file, FileMode.Open)); using (var bw = new BinaryWriter(fs)) { WriteWave(bw, (decoder.Stereo ? 2 : 1), decoder.SampleRate, decoder.SelectMany(chunk => chunk.Bytes.Take(chunk.Length)).ToArray()); bw.Close(); } fs.Close(); } } }
public AudioDataCs GetSampleFromArray(byte[] data) { Stream stream = new MemoryStream(data); if (stream.ReadByte() == 'R' && stream.ReadByte() == 'I' && stream.ReadByte() == 'F' && stream.ReadByte() == 'F') { stream.Position = 0; int channels, bits_per_sample, sample_rate; byte[] sound_data = LoadWave(stream, out channels, out bits_per_sample, out sample_rate); AudioDataCs sample = new AudioDataCs() { Pcm = sound_data, BitsPerSample = bits_per_sample, Channels = channels, Rate = sample_rate, }; return sample; } else { stream.Position = 0; AudioDataCs sample = new OggDecoder().OggToWav(stream); return sample; } }
public SoundEffect Convert(string path) { string wavPath = path.Replace(".ogg", ".wav"); SoundEffect soundEffect = null; int c = 0; Exception le = null; bool done = false; while (!done && c < ti) { FileStream stream = new FileStream(wavPath, FileMode.Create); try { using (BinaryWriter writer = new BinaryWriter(stream)) { OggDecoder decoder = new OggDecoder(); decoder.Initialize(File.OpenRead(path)); byte[] data = decoder.SelectMany(chunk => chunk.Bytes.Take(chunk.Length)).ToArray(); WriteWave(writer, decoder.Stereo ? 2 : 1, decoder.SampleRate, data); } } catch (Exception e) { le = e; c++; Thread.Sleep(slp); } done = true; stream.Close(); stream.Dispose(); } int d = 0; while (soundEffect == null && d < ti) { FileStream stream = stream = new FileStream(wavPath, FileMode.Open); try { soundEffect = SoundEffect.FromStream(stream); } catch (Exception e) { le = e; d++; Thread.Sleep(slp); } stream.Close(); stream.Dispose(); } /*if(soundEffect == null) * Monitor.Log(path + ":" + le.Message + ":" + le.StackTrace, LogLevel.Trace);*/ return(soundEffect); }
/// <summary> /// Initializes a new instance of the <see cref="OggSharpSource" /> class. /// </summary> /// <param name="stream"><see cref="Stream" /> which contains raw waveform-audio data.</param> /// <param name="waveFormat">The format of the waveform-audio data within the <paramref name="stream" />.</param> /// <param name="chunks">the wave chunks read using the wavefile reader</param> public OggSharpSource(Stream stream, WaveFormat waveFormat, ReadOnlyCollection <WaveFileChunk> chunks) { if (stream == null) { throw new ArgumentNullException("stream"); } if (!stream.CanRead) { throw new ArgumentException("stream is not readable", "stream"); } // format checking if the ogg is within a wav container if (waveFormat != null) { switch ((short)waveFormat.WaveFormatTag) { case 0x674f: // OGG_VORBIS_MODE_1 "Og" Original stream compatible case 0x676f: // OGG_VORBIS_MODE_1_PLUS "og" Original stream compatible case 0x6750: // OGG_VORBIS_MODE_2 "Pg" Have independent header case 0x6770: // OGG_VORBIS_MODE_2_PLUS "pg" Have independent headere case 0x6751: // OGG_VORBIS_MODE_3 "Qg" Have no codebook header case 0x6771: // OGG_VORBIS_MODE_3_PLUS "qg" Have no codebook header break; default: throw new ArgumentException(string.Format("Not supported encoding: {0}", waveFormat.WaveFormatTag)); } } // format checking if the ogg is within a wav container if (chunks != null) { // check format var audioFormat = new AudioFormat(); var fmtChunk = (FmtChunk)chunks.FirstOrDefault(x => x is FmtChunk); if (fmtChunk != null) { // https://github.com/chirlu/sox/blob/4927023d0978615c74e8a511ce981cf4c29031f1/src/wav.c long oldPosition = stream.Position; long startPosition = fmtChunk.StartPosition; long endPosition = fmtChunk.EndPosition; long chunkDataSize = fmtChunk.ChunkDataSize; stream.Position = startPosition; var reader = new BinaryReader(stream); audioFormat.Encoding = (AudioEncoding)reader.ReadInt16(); audioFormat.Channels = reader.ReadInt16(); audioFormat.SampleRate = reader.ReadInt32(); audioFormat.AverageBytesPerSecond = reader.ReadInt32(); audioFormat.BlockAlign = reader.ReadInt16(); audioFormat.BitsPerSample = reader.ReadInt16(); if (fmtChunk.ChunkDataSize > 16) { audioFormat.ExtraSize = reader.ReadInt16(); if (audioFormat.ExtraSize >= 2) { audioFormat.SamplesPerBlock = reader.ReadInt16(); } } // reset position stream.Position = oldPosition; reader = null; } var dataChunk = (DataChunk)chunks.FirstOrDefault(x => x is DataChunk); if (dataChunk != null) { audioFormat.DataChunkSize = dataChunk.ChunkDataSize; } else { throw new ArgumentException("The specified stream does not contain any data chunks."); } Log.Verbose(audioFormat.ToString()); } // set stream _stream = stream; // TODO: check with reference implementation // https://github.com/xiph/vorbis _oggDecoder = new OggDecoder(); // if the ogg content is embedded in a wave file, copy whole stream into memory if (waveFormat != null) { MemoryStream memoryStream = new MemoryStream(); stream.CopyTo(memoryStream); memoryStream.Position = 0; _oggDecoder.Initialize(memoryStream); _oggPCMChunkEnumerator = _oggDecoder.GetEnumerator(); } else { _oggDecoder.Initialize(stream); _oggPCMChunkEnumerator = _oggDecoder.GetEnumerator(); } int channels = _oggDecoder.Channels; int sampleRate = _oggDecoder.SampleRate; Log.Verbose(string.Format("Ogg Vorbis bitstream is {0} channel, {1} Hz", channels, sampleRate)); Log.Verbose(string.Format("Comment: {0}", _oggDecoder.Comment)); Log.Verbose(string.Format("Encoded by: {0}", _oggDecoder.Vendor)); _waveFormat = new WaveFormat(sampleRate, 16, channels, AudioEncoding.Pcm); // store length in bytes according to the new waveformat _length = WaveFormat.SecondsToBytes(_oggDecoder.Length); }
AudioSample GetSample(string filename) { if (!audio.cache.ContainsKey(filename)) { Stream stream = audio.d_GetFile.GetFile(filename); if (stream.ReadByte() == 'R' && stream.ReadByte() == 'I' && stream.ReadByte() == 'F' && stream.ReadByte() == 'F') { stream.Position = 0; int channels, bits_per_sample, sample_rate; byte[] sound_data = LoadWave(stream, out channels, out bits_per_sample, out sample_rate); AudioSample sample = new AudioSample() { Pcm = sound_data, BitsPerSample = bits_per_sample, Channels = channels, Rate = sample_rate, }; audio.cache[filename] = sample; } else { stream.Position = 0; AudioSample sample = new OggDecoder().OggToWav(stream); audio.cache[filename] = sample; } } return audio.cache[filename]; }