private static void Conversion() { string filename = "audio_bin2"; byte[] myBytes =File.ReadAllBytes(filename); // entre 0 et 255 short short[] myShort = new short[myBytes.Length]; // entre 0 et | 257 short[] myShortDouble = new short[myBytes.Length*2]; byte[] myBytes16MHz = new byte[myShortDouble.Length * 2]; int short_intervalle = short.MaxValue - short.MinValue; int multiplieur = short_intervalle/Byte.MaxValue; for (int i = 0; i < myBytes.Length; i++) { short sh = myBytes[i]; int tampon = short.MinValue + (sh * multiplieur); myShort[i] = (short)(tampon); } for (int i = 0; i < myShort.Length; i++) { myShortDouble[2*i] = myShort[i]; if (i < myShort.Length-1) { short half1 = (short)(myShort[i] / 2); short half2 = (short)(myShort[i + 1] / 2); myShortDouble[2 * i + 1] = (short)(half1 + half2); } if (i == myShort.Length - 1) { myShortDouble[2 * i+1] = myShort[i]; } } for (int i = 0; i < myShortDouble.Length; i++) { myBytes16MHz[2*i] = (byte)myShortDouble[i]; myBytes16MHz[2*i+1] = (byte)(myShortDouble[i] >> 8); } /* DateTime d = DateTime.Now; string datePatt = @"Mdyyyyhhmmsstt"; string filename2 = "audio_raw_" + d.ToString(datePatt); FileStream fileStream2 = new FileStream(filename2, FileMode.Create); fileStream2.Write((byte[])myBytes16MHz, 0, myBytes16MHz.Length); fileStream2.Close();*///MemoryStream get buffer DateTime d = DateTime.Now; string datePatt = @"Mdyyyyhhmmsstt"; Console.WriteLine("Conversion finie !!"); string outputFile = "audio_flac_" + d.ToString(datePatt) + ".flac"; FlakeWriter flac = new FlakeWriter(null, 16, 1, 16000, File.Create(outputFile)); //FlacWriter flac = new FlacWriter(File.Create(outputFile), 16, 1, 16000); //flac.Write(myBytes16MHz, 0, myBytes16MHz.Length); //flac.Write(); flac.Close(); }
private static Tuple<int, string> WavToFlacHelper(WAVReader audioSource, string targetFlacPath) { int sampleRate; AudioBuffer buffer = new AudioBuffer(audioSource, 0x10000); FlakeWriterSettings settings = new FlakeWriterSettings(); settings.PCM = audioSource.PCM; FlakeWriter audioDestination = new FlakeWriter(targetFlacPath, settings); while (audioSource.Read(buffer, -1) != 0) { audioDestination.Write(buffer); } sampleRate = settings.PCM.SampleRate; audioDestination.Close(); audioSource.Close(); return new Tuple<int, string>(sampleRate, targetFlacPath); }
/// <summary> Конвертирование wav-файла во flac </summary> /// <returns>Частота дискретизации</returns> public static int Wav2Flac(Stream wavStream, Stream flacStream) { int sampleRate = 0; IAudioSource audioSource = new WAVReader(null, wavStream); AudioBuffer buff = new AudioBuffer(audioSource, 0x10000); FlakeWriter flakewriter = new FlakeWriter(null, flacStream, audioSource.PCM); sampleRate = audioSource.PCM.SampleRate; FlakeWriter audioDest = flakewriter; while (audioSource.Read(buff, -1) != 0) { audioDest.Write(buff); } return sampleRate; }
public static int Wav2Flac(String wavName, string flacName) { int sampleRate = 0; IAudioSource audioSource = new WAVReader(wavName, null); AudioBuffer buff = new AudioBuffer(audioSource, 0x10000); FlakeWriter flakewriter = new FlakeWriter(flacName, audioSource.PCM); sampleRate = audioSource.PCM.SampleRate; FlakeWriter audioDest = flakewriter; while (audioSource.Read(buff, -1) != 0) { audioDest.Write(buff); } audioDest.Close(); audioDest.Close(); audioSource.Close(); return sampleRate; }
private byte[] Wav2FlacBuffConverter(byte[] Buffer) { Stream OutWavStream = new MemoryStream(); Stream OutFlacStream = new MemoryStream(); AudioPCMConfig pcmconf = new AudioPCMConfig(16, 1, 16000); WAVWriter wr = new WAVWriter(null, OutWavStream, pcmconf); wr.Write(new AudioBuffer(pcmconf, Buffer, Buffer.Length / 2)); OutWavStream.Seek(0, SeekOrigin.Begin); WAVReader audioSource = new WAVReader(null, OutWavStream); if (audioSource.PCM.SampleRate != 16000) return null; AudioBuffer buff = new AudioBuffer(audioSource, 0x10000); FlakeWriter flakeWriter = new FlakeWriter(null, OutFlacStream, audioSource.PCM); flakeWriter.CompressionLevel = 8; while (audioSource.Read(buff, -1) != 0) { flakeWriter.Write(buff); } OutFlacStream.Seek(0, SeekOrigin.Begin); byte[] barr = new byte[OutFlacStream.Length]; OutFlacStream.Read(barr, 0, (int)OutFlacStream.Length); return barr; }
public async Task TestWriting() { var wavStream = await (await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///test.wav"))) .OpenStreamForReadAsync(); var expectedBytes = ReadFully(await (await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///flake.flac"))) .OpenStreamForReadAsync()); var buff = WAVReader.ReadAllSamples(wavStream); FlakeWriter target; var outputStream = new MemoryStream(); target = new FlakeWriter(outputStream, new FlakeWriterSettings { PCM = buff.PCM, EncoderMode = "7" }); target.Settings.Padding = 1; target.DoSeekTable = false; target.Write(buff); target.Close(); outputStream.Seek(0, SeekOrigin.Begin); var resultContent = outputStream.ToArray(); var outStream = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync("out.flac", CreationCollisionOption.ReplaceExisting); outStream.Write(resultContent, 0, resultContent.Length); outStream.Dispose(); Debug.WriteLine(ApplicationData.Current.LocalFolder.Path); CollectionAssert.AreEqual(expectedBytes, outputStream.ToArray(), "result and expected doesn't match."); }
public void TestWriting() { AudioBuffer buff = WAVReader.ReadAllSamples("test.wav", null); FlakeWriter target; target = new FlakeWriter("flakewriter0.flac", null, new FlakeWriterSettings { PCM = buff.PCM, EncoderMode = "7" }); target.Settings.Padding = 1; target.DoSeekTable = false; //target.Vendor = "CUETools"; //target.CreationTime = DateTime.Parse("15 Aug 1976"); target.FinalSampleCount = buff.Length; target.Write(buff); target.Close(); //CollectionAssert.AreEqual(File.ReadAllBytes("flake.flac"), File.ReadAllBytes("flakewriter0.flac"), "flakewriter0.flac doesn't match."); target = new FlakeWriter("flakewriter1.flac", null, new FlakeWriterSettings { PCM = buff.PCM, EncoderMode = "7" }); target.Settings.Padding = 1; target.DoSeekTable = false; //target.Vendor = "CUETools"; //target.CreationTime = DateTime.Parse("15 Aug 1976"); target.Write(buff); target.Close(); CollectionAssert.AreEqual(File.ReadAllBytes("flake.flac"), File.ReadAllBytes("flakewriter1.flac"), "flakewriter1.flac doesn't match."); }
private void ConvertToFlac(Stream sourceStream, Stream destinationStream) { var audioSource = new WAVReader(null, sourceStream); try { if (audioSource.PCM.SampleRate != 16000) { throw new InvalidOperationException("Incorrect frequency - WAV file must be at 16 KHz."); } var buff = new AudioBuffer(audioSource, 0x10000); var flakeWriter = new FlakeWriter(null, destinationStream, audioSource.PCM); // flakeWriter.CompressionLevel = 8; while (audioSource.Read(buff, -1) != 0) { flakeWriter.Write(buff); } flakeWriter.Close(); } finally { audioSource.Close(); } }
/// <summary> /// Convert stream of wav to flac format and send it to google speech recognition service. /// </summary> /// <param name="stream">wav stream</param> /// <returns>recognized result</returns> /// // Step 1- Converts wav stream to flac public static string WavStreamToGoogle(Stream stream) { FlakeWriter audioDest = null; IAudioSource audioSource = null; string answer; try { var outStream = new MemoryStream(); stream.Position = 0; audioSource = new WAVReader("", stream); var buff = new AudioBuffer(audioSource, 0x10000); audioDest = new FlakeWriter("", outStream, audioSource.PCM); var sampleRate = audioSource.PCM.SampleRate; while (audioSource.Read(buff, -1) != 0) { audioDest.Write(buff); } answer = GoogleRequest(outStream, sampleRate); } finally { if (audioDest != null) audioDest.Close(); if (audioSource != null) audioSource.Close(); } return answer; }
/// <summary> /// Convert .wav file to .flac file with the same name /// </summary> /// <param name="WavName">path to .wav file</param> /// <returns>Sample Rate of converted .flac</returns> public static int Wav2Flac(string WavName) { int sampleRate; var flacName = Path.ChangeExtension(WavName, "flac"); FlakeWriter audioDest = null; IAudioSource audioSource = null; try { audioSource = new WAVReader(WavName, null); AudioBuffer buff = new AudioBuffer(audioSource, 0x10000); audioDest = new FlakeWriter(flacName, audioSource.PCM); sampleRate = audioSource.PCM.SampleRate; while (audioSource.Read(buff, -1) != 0) { audioDest.Write(buff); } } finally { if (audioDest != null) audioDest.Close(); if (audioSource != null) audioSource.Close(); } return sampleRate; }
/// <summary>Конвертирование wav-файла во flac</summary> /// <returns>Частота дискретизации</returns> private static void _Wav2Flac(String wavName, string flacName) { Debug.Assert(wavName != null); Debug.Assert(!string.IsNullOrEmpty(flacName)); IAudioSource audioSource = new WAVReader(wavName, null); AudioBuffer buff = new AudioBuffer(audioSource, 0x10000); FlakeWriter flakewriter = new FlakeWriter(flacName, audioSource.PCM); FlakeWriter audioDest = flakewriter; while (audioSource.Read(buff, -1) != 0) { audioDest.Write(buff); } audioDest.Close(); audioSource.Close(); }
static int Main(string[] args) { TextWriter stdout = Console.Out; Console.SetOut(Console.Error); DateTime start = DateTime.Now; TimeSpan lastPrint = TimeSpan.FromMilliseconds(0); bool debug = false, quiet = false; string prediction_type = null; string stereo_method = null; string window_method = null; string order_method = null; string window_function = null; string input_file = null; string output_file = null; int min_partition_order = -1, max_partition_order = -1, min_lpc_order = -1, max_lpc_order = -1, min_fixed_order = -1, max_fixed_order = -1, min_precision = -1, max_precision = -1, blocksize = -1, estimation_depth = -1; int level = -1, padding = -1, vbr_mode = -1; bool do_md5 = true, do_seektable = true, do_verify = false; bool buffered = false; for (int arg = 0; arg < args.Length; arg++) { bool ok = true; if (args[arg].Length == 0) ok = false; else if (args[arg] == "--debug") debug = true; else if ((args[arg] == "-q" || args[arg] == "--quiet")) quiet = true; else if (args[arg] == "--verify") do_verify = true; else if (args[arg] == "--no-seektable") do_seektable = false; else if (args[arg] == "--no-md5") do_md5 = false; else if (args[arg] == "--buffered") buffered = true; else if ((args[arg] == "-o" || args[arg] == "--output") && ++arg < args.Length) output_file = args[arg]; else if ((args[arg] == "-t" || args[arg] == "--prediction-type") && ++arg < args.Length) prediction_type = args[arg]; else if ((args[arg] == "-s" || args[arg] == "--stereo") && ++arg < args.Length) stereo_method = args[arg]; else if ((args[arg] == "-m" || args[arg] == "--order-method") && ++arg < args.Length) order_method = args[arg]; else if ((args[arg] == "-w" || args[arg] == "--window") && ++arg < args.Length) window_function = args[arg]; else if (args[arg] == "--window-method" && ++arg < args.Length) window_method = args[arg]; else if ((args[arg] == "-r" || args[arg] == "--partition-order") && ++arg < args.Length) { ok = (args[arg].Split(',').Length == 2 && int.TryParse(args[arg].Split(',')[0], out min_partition_order) && int.TryParse(args[arg].Split(',')[1], out max_partition_order)) || int.TryParse(args[arg], out max_partition_order); } else if ((args[arg] == "-l" || args[arg] == "--lpc-order") && ++arg < args.Length) { ok = (args[arg].Split(',').Length == 2 && int.TryParse(args[arg].Split(',')[0], out min_lpc_order) && int.TryParse(args[arg].Split(',')[1], out max_lpc_order)) || int.TryParse(args[arg], out max_lpc_order); } else if ((args[arg] == "-f" || args[arg] == "--fixed-order") && ++arg < args.Length) { ok = (args[arg].Split(',').Length == 2 && int.TryParse(args[arg].Split(',')[0], out min_fixed_order) && int.TryParse(args[arg].Split(',')[1], out max_fixed_order)) || int.TryParse(args[arg], out max_fixed_order); } else if ((args[arg] == "-e" || args[arg] == "--estimation-depth") && ++arg < args.Length) ok = int.TryParse(args[arg], out estimation_depth); else if ((args[arg] == "-c" || args[arg] == "--max-precision") && ++arg < args.Length) { ok = (args[arg].Split(',').Length == 2 && int.TryParse(args[arg].Split(',')[0], out min_precision) && int.TryParse(args[arg].Split(',')[1], out max_precision)) || int.TryParse(args[arg], out max_precision); } else if ((args[arg] == "-v" || args[arg] == "--vbr")) ok = (++arg < args.Length) && int.TryParse(args[arg], out vbr_mode); else if ((args[arg] == "-b" || args[arg] == "--blocksize") && ++arg < args.Length) ok = int.TryParse(args[arg], out blocksize); else if ((args[arg] == "-p" || args[arg] == "--padding") && ++arg < args.Length) ok = int.TryParse(args[arg], out padding); else if (args[arg] != "-" && args[arg][0] == '-' && int.TryParse(args[arg].Substring(1), out level)) ok = level >= 0 && level <= 11; else if ((args[arg][0] != '-' || args[arg] == "-") && input_file == null) input_file = args[arg]; else ok = false; if (!ok) { Usage(); return 1; } } if (input_file == null || ((input_file == "-" || Path.GetExtension(input_file) == ".flac") && output_file == null)) { Usage(); return 2; } if (!quiet) { Console.WriteLine("CUETools.Flake, Copyright (C) 2009 Grigory Chudov."); Console.WriteLine("Based on Flake encoder by Justin Ruggles, <http://flake-enc.sourceforge.net/>."); Console.WriteLine("This is free software under the GNU GPLv3+ license; There is NO WARRANTY, to"); Console.WriteLine("the extent permitted by law. <http://www.gnu.org/licenses/> for details."); } IAudioSource audioSource; if (input_file == "-") audioSource = new WAVReader("", Console.OpenStandardInput()); else if (File.Exists(input_file) && Path.GetExtension(input_file) == ".wav") audioSource = new WAVReader(input_file, null); else if (File.Exists(input_file) && Path.GetExtension(input_file) == ".flac") audioSource = new FlakeReader(input_file, null); else { Usage(); return 3; } if (buffered) audioSource = new AudioPipe(audioSource, 0x10000); if (output_file == null) output_file = Path.ChangeExtension(input_file, "flac"); FlakeWriter flake = new FlakeWriter((output_file == "-" || output_file == "nul") ? "" : output_file, output_file == "-" ? Console.OpenStandardOutput() : output_file == "nul" ? new NullStream() : null, audioSource.PCM); flake.FinalSampleCount = audioSource.Length; IAudioDest audioDest = flake; AudioBuffer buff = new AudioBuffer(audioSource, 0x10000); try { if (level >= 0) flake.CompressionLevel = level; if (prediction_type != null) flake.PredictionType = Flake.LookupPredictionType(prediction_type); if (stereo_method != null) flake.StereoMethod = Flake.LookupStereoMethod(stereo_method); if (window_method != null) flake.WindowMethod = Flake.LookupWindowMethod(window_method); if (order_method != null) flake.OrderMethod = Flake.LookupOrderMethod(order_method); if (window_function != null) flake.WindowFunction = Flake.LookupWindowFunction(window_function); if (min_partition_order >= 0) flake.MinPartitionOrder = min_partition_order; if (max_partition_order >= 0) flake.MaxPartitionOrder = max_partition_order; if (min_lpc_order >= 0) flake.MinLPCOrder = min_lpc_order; if (max_lpc_order >= 0) flake.MaxLPCOrder = max_lpc_order; if (min_fixed_order >= 0) flake.MinFixedOrder = min_fixed_order; if (max_fixed_order >= 0) flake.MaxFixedOrder = max_fixed_order; if (max_precision >= 0) flake.MaxPrecisionSearch = max_precision; if (min_precision >= 0) flake.MinPrecisionSearch = min_precision; if (blocksize >= 0) flake.BlockSize = blocksize; if (estimation_depth >= 0) flake.EstimationDepth = estimation_depth; if (padding >= 0) flake.Padding = padding; if (vbr_mode >= 0) flake.VBRMode = vbr_mode; flake.DoSeekTable = do_seektable; (flake.Settings as FlakeWriterSettings).DoVerify = do_verify; (flake.Settings as FlakeWriterSettings).DoMD5 = do_md5; } catch (Exception ex) { Usage(); Console.WriteLine(""); Console.WriteLine("Error: {0}.", ex.Message); return 4; } if (!quiet) { Console.WriteLine("Filename : {0}", input_file); Console.WriteLine("File Info : {0}kHz; {1} channel; {2} bit; {3}", audioSource.PCM.SampleRate, audioSource.PCM.ChannelCount, audioSource.PCM.BitsPerSample, TimeSpan.FromSeconds(audioSource.Length * 1.0 / audioSource.PCM.SampleRate)); } #if !DEBUG try #endif { while (audioSource.Read(buff, -1) != 0) { audioDest.Write(buff); TimeSpan elapsed = DateTime.Now - start; if (!quiet) { if ((elapsed - lastPrint).TotalMilliseconds > 60) { Console.Error.Write("\rProgress : {0:00}%; {1:0.00}x; {2}/{3}", 100.0 * audioSource.Position / audioSource.Length, audioSource.Position / elapsed.TotalSeconds / audioSource.PCM.SampleRate, elapsed, TimeSpan.FromMilliseconds(elapsed.TotalMilliseconds / audioSource.Position * audioSource.Length) ); lastPrint = elapsed; } } } audioDest.Close(); } #if !DEBUG catch (Exception ex) { Console.Error.Write("\r \r"); Console.WriteLine("Error : {0}", ex.Message); audioDest.Delete(); audioSource.Close(); return 5; } #endif TimeSpan totalElapsed = DateTime.Now - start; if (!quiet) { Console.Error.Write("\r \r"); Console.WriteLine("Results : {0:0.00}x; {2} bytes in {1} seconds;", audioSource.Position / totalElapsed.TotalSeconds / audioSource.PCM.SampleRate, totalElapsed, flake.TotalSize ); } audioSource.Close(); if (debug) { Console.SetOut(stdout); Console.Out.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}..{7}\t{8}..{9}\t{10}..{11}\t{12}..{13}\t{14}\t{15}", flake.TotalSize, flake.UserProcessorTime.TotalSeconds > 0 ? flake.UserProcessorTime.TotalSeconds : totalElapsed.TotalSeconds, flake.PredictionType.ToString().PadRight(15), flake.StereoMethod.ToString().PadRight(15), (flake.OrderMethod.ToString() + "(" + flake.EstimationDepth.ToString() + ")").PadRight(15), flake.WindowFunction, flake.MinPartitionOrder, flake.MaxPartitionOrder, flake.MinLPCOrder, flake.MaxLPCOrder, flake.MinFixedOrder, flake.MaxFixedOrder, flake.MinPrecisionSearch, flake.MaxPrecisionSearch, flake.BlockSize, flake.VBRMode ); } return 0; }
private static byte[] WaveSamplesToFlake(byte[] combinedChunks) { var audioBuffer = new AudioBuffer(new AudioPCMConfig(16, 1, 22050), combinedChunks, combinedChunks.Length/2); byte[] flakeBuffer; using (var flakeStream = new MemoryStream()) { var flakeWriter = new FlakeWriter(null, flakeStream, new FlakeWriterSettings {PCM = audioBuffer.PCM, EncoderMode = "7"}); flakeWriter.Settings.Padding = 1; flakeWriter.DoSeekTable = false; flakeWriter.FinalSampleCount = audioBuffer.Length; flakeWriter.Write(audioBuffer); flakeStream.Position = 0; using (var br = new BinaryReader(flakeStream)) { flakeBuffer = new byte[flakeStream.Length]; br.Read(flakeBuffer, 0, flakeBuffer.Length); } } return flakeBuffer; }
private byte[] Wav2Flac(MemoryStream waveStreamMemory) { if (waveStreamMemory.Length >= 3200) // 0 { Log.Write("Ева услышала Вас.", Log.Category.Information); byte[] Array = null; WaveFileWriter writer = new WaveFileWriter("C:\\rec_temp.wav", waveInEvent.WaveFormat); writer.Write(waveStreamMemory.ToArray(), 0, waveStreamMemory.ToArray().Length); writer.Close(); IAudioSource audioSource = new WAVReader("C:\\rec_temp.wav", null); AudioPCMConfig audioPCMConfig = new AudioPCMConfig(16, 1, 16000); AudioBuffer buff = new AudioBuffer(audioSource, 0x10000); //AudioBuffer buffMemory = new AudioBuffer(audioPCMConfig, waveStreamMemory.ToArray(), Convert.ToInt32(waveStreamMemory.Length) / audioPCMConfig.BlockAlign); FlakeWriter flakewriter = new FlakeWriter(null, audioSource.PCM); FlakeWriter audioDest = flakewriter; while (audioSource.Read(buff, -1) != 0) { audioDest.Write(buff); } if (flakewriter.BufferMemory != null) { Array = flakewriter.BufferMemory.ToArray(); } audioDest.Close(); audioSource.Close(); return Array; } return null; }