public override float[] ReadMonoFromFile(string pathToFile, int sampleRate, int secondsToRead, int startAtSecond) { using (var reader = new MediaFoundationReader(pathToFile)) { int actualSampleRate = reader.WaveFormat.SampleRate; int bitsPerSample = reader.WaveFormat.BitsPerSample; reader.Seek(actualSampleRate * bitsPerSample / 8 * startAtSecond, System.IO.SeekOrigin.Begin); using (var resampler = new MediaFoundationResampler(reader, WaveFormat.CreateIeeeFloatWaveFormat(sampleRate, 1))) { float[] buffer = new float[sampleRate * 20]; // 20 seconds buffer List<float[]> chunks = new List<float[]>(); int totalFloatsToRead = secondsToRead == 0 ? int.MaxValue : secondsToRead * sampleRate; int totalFloatsRead = 0; Pcm32BitToSampleProvider pcmReader = new Pcm32BitToSampleProvider(resampler); while (totalFloatsRead < totalFloatsToRead) { // get re-sampled/mono data int floatsRead = pcmReader.Read(buffer, 0, buffer.Length); if (floatsRead == 0) { break; } totalFloatsRead += floatsRead; float[] chunk; if (totalFloatsRead > totalFloatsToRead) { chunk = new float[(totalFloatsToRead - (totalFloatsRead - floatsRead))]; Array.Copy(buffer, chunk, totalFloatsToRead - (totalFloatsRead - floatsRead)); } else { chunk = new float[floatsRead]; // each float contains 4 bytes Array.Copy(buffer, chunk, floatsRead); } chunks.Add(chunk); } if (totalFloatsRead < (secondsToRead * sampleRate)) { return null; /*not enough samples to return the requested data*/ } float[] data = ConcatenateChunksOfSamples(chunks); return data; } } }
/// <summary> /// Convert a MP3 file to WAV. /// </summary> /// <param name="filePath">The path to MP3 file.</param> /// <param name="outputFolder">The path to output folder</param> /// <param name="outputSampleRate">The sample rate for the output wav file (default: 16kHz)</param> /// <returns>The path to created WAV file.</returns> public static string Mp3ToWav(string filePath, string outputFolder, int outputSampleRate = 16000) { if (Path.GetExtension(filePath).ToLower() != ".mp3") { throw new AudioException("The input file must be a MP3 audio file."); } string outFile = string.Format("{0}/{1}.wav", outputFolder, Path.GetFileNameWithoutExtension(filePath)); using (Mp3FileReader mp3reader = new Mp3FileReader(filePath)) { if (!Directory.Exists(outputFolder)) { Directory.CreateDirectory(outputFolder); } var outFormat = new WaveFormat(outputSampleRate, mp3reader.WaveFormat.Channels); using (var resampler = new MediaFoundationResampler(mp3reader, outFormat)) { WaveFileWriter.CreateWaveFile(outFile, resampler); } } return(outFile); }
private byte[] ResampleAudio(Stream inputData, WaveFormat inputFormat, WaveFormat outputFormat) { if (inputData.CanSeek) { inputData.Seek(0, SeekOrigin.Begin); } using (var ms = new MemoryStream()) { using (var reader = new RawSourceWaveStream(inputData, inputFormat)) { using (var resampler = new MediaFoundationResampler(reader, outputFormat)) { resampler.ResamplerQuality = 60; WaveFileWriter.WriteWavFileToStream(ms, resampler); return(ms.ToArray()); } } } }
public static void WriteAudioBufferToFile() { try { if (WasapiLoopbackCapture != null) { Directory.CreateDirectory(ApplicationConfiguration.Instance.SoundboardSampleDirectory); string fileName = $"AudioSample_{DateTime.Now.ToString("yyyyMMddHHmmss")}.wav"; string fileNameFull = Path.Combine(ApplicationConfiguration.Instance.SoundboardSampleDirectory, fileName); using (WaveFileWriter waveFileWriter = new WaveFileWriter(fileNameFull, WasapiLoopbackCapture.WaveFormat)) { int audioSampleSize = ApplicationConfiguration.Instance.SoundboardSampleSeconds * WasapiLoopbackCapture.WaveFormat.AverageBytesPerSecond; var bytesToWrite = audioSampleSize > _audioByteBuffer.Count ? _audioByteBuffer.ToArray() : _audioByteBuffer.GetRange(_audioByteBuffer.Count - audioSampleSize, audioSampleSize).ToArray(); waveFileWriter.Write(bytesToWrite, 0, bytesToWrite.Length); } _audioByteBuffer.Clear(); // Resample if necessary if (ApplicationConfiguration.Instance.RecordingSampleRate != -1) { using (var audioFileReader = new AudioFileReader(fileNameFull)) using (var mediaFoundationResampler = new MediaFoundationResampler(audioFileReader, ApplicationConfiguration.Instance.RecordingSampleRate)) { WaveFileWriter.CreateWaveFile($"{fileNameFull}.BAK", mediaFoundationResampler); } File.Delete(fileNameFull); File.Move($"{fileNameFull}.BAK", fileNameFull); } AudioAgent.FileWritten?.Invoke(fileNameFull, EventArgs.Empty); } } catch (Exception ex) { ApplicationLogger.Log(ex.Message, ex.StackTrace); } }
public async Task SendAudio(Channel channel, Song song) { try { MyBot.Log(DateTime.Now.ToUniversalTime().ToShortTimeString() + " - " + channel.Name + ") Song playing: " + song.path, channel.Name + "_log"); var channelCount = discordClient.GetService <AudioService>().Config.Channels; // Get the number of AudioChannels our AudioService has been configured to use. var OutFormat = new WaveFormat(48000, 16, 2); // Create a new Output Format, using the spec that Discord will accept, and with the number of channels that our client supports. using (var MP3Reader = new Mp3FileReader(song.path)) // Create a new Disposable MP3FileReader, to read audio from the filePath parameter using (var resampler = new MediaFoundationResampler(MP3Reader, OutFormat)) // Create a Disposable Resampler, which will convert the read MP3 data to PCM, using our Output Format { resampler.ResamplerQuality = 60; // Set the quality of the resampler to 60, the highest quality int blockSize = OutFormat.AverageBytesPerSecond / 50; // Establish the size of our AudioBuffer byte[] buffer = new byte[blockSize]; int byteCount; await channel.SendMessage("Playing *" + song.user + "'s* song **" + song.title + "** now!"); MyBot.Log("Playing *" + song.user + "'s* song **" + song.title + "** now!", "music_log"); while (playing && !skipped && (byteCount = resampler.Read(buffer, 0, blockSize)) > 0) // Read audio into our buffer, and keep a loop open while data is present { if (byteCount < blockSize) { // Incomplete Frame for (int i = byteCount; i < blockSize; i++) { buffer[i] = 0; } } discordAudio.Send(buffer, 0, blockSize); // Send the buffer to Discord } if (skipped) { skipped = false; } } } catch (Exception e) { await channel.SendMessage("Something went teribly wrong.. ABORT ABORT \\o/"); Console.WriteLine(e.StackTrace); } }
public static byte[] ResampleAudio(byte[] inputFrame, int inputSampleRate, int inputBitsPerSample, int inputChannelCount, int outSampleRate) { byte[] outFrame; if (inputSampleRate != outSampleRate) { IWaveProvider provider = new RawSourceWaveStream(new MemoryStream(inputFrame), new WaveFormat(inputSampleRate, inputBitsPerSample, inputChannelCount)); var outFormat = new WaveFormat(outSampleRate, provider.WaveFormat.Channels); using (var resampler = new MediaFoundationResampler(provider, outFormat)) { resampler.ResamplerQuality = 1; int wavHeaderSize = Config.AudioSettings.WAV_HEADER_SIZE; int outBufferLength = outFormat.AverageBytesPerSecond / 100; int wavBufferLength = outBufferLength + wavHeaderSize; MemoryStream outStream = new MemoryStream(wavBufferLength); WaveFileWriter.WriteWavFileToStream(outStream, resampler); byte[] wavBytes = new byte[wavBufferLength]; Array.Copy(outStream.ToArray(), wavBytes, outStream.Length); if (outStream.Length < wavBufferLength) { Array.Copy(new byte[wavBufferLength - outStream.Length], 0, wavBytes, outStream.Length, wavBufferLength - outStream.Length); } ArraySegment <byte> outArraySegment = new ArraySegment <byte>(wavBytes, wavHeaderSize, outBufferLength); outFrame = outArraySegment.ToArray(); } } else { outFrame = inputFrame; } return(outFrame); }
private void convertAudioSample(int sampleRate, string waveFile) { string inPath = dirPath + waveFile; string outPath = tempDirPath + "/" + waveFile; using (var reader = new WaveFileReader(inPath)) { var outFormat = new WaveFormat(sampleRate, reader.WaveFormat.Channels); using (var resampler = new MediaFoundationResampler(reader, outFormat)) { WaveFileWriter.CreateWaveFile(outPath, resampler); using (var newSample = new WaveFileReader(outPath)) { newWavNames.Add(waveFile); Console.WriteLine("New sample rate: " + newSample.SampleCount + " FOR " + waveFile); } } } }
public void SendAudio(string filePath) // Audio sending control { var channelCount = bot.GetService <AudioService>().Config.Channels; // Get the number of AudioChannels our AudioService has been configured to use. var OutFormat = new WaveFormat(48000, 16, channelCount); // Create a new Output Format, using the spec that Discord will accept, and with the number of channels that our client supports. using (var MP3Reader = new Mp3FileReader(filePath)) // Create a new Disposable MP3FileReader, to read audio from the filePath parameter using (var resampler = new MediaFoundationResampler(MP3Reader, OutFormat)) // Create a Disposable Resampler, which will convert the read MP3 data to PCM, using our Output Format { resampler.ResamplerQuality = 60; // Set the quality of the resampler to 60, the highest quality int blockSize = OutFormat.AverageBytesPerSecond / 50; // Establish the size of our AudioBuffer byte[] buffer = new byte[blockSize]; int byteCount; while ((byteCount = resampler.Read(buffer, 0, blockSize)) > 0) // Read audio into our buffer, and keep a loop open while data is present { if (byteCount < blockSize) { // Incomplete Frame for (int i = byteCount; i < blockSize; i++) { buffer[i] = 0; } } _vClient.Send(buffer, 0, blockSize); // Send the buffer to Discord if (_isPaused) { do { } while (_isPaused); } if (_isStopped) { break; } } _vClient.Disconnect(); _isStopped = true; _isPaused = false; Connected = false; } }
private void RepositionTest() { if (String.IsNullOrEmpty(InputFile)) { MessageBox.Show("Select a file first"); return; } var saveFile = SelectSaveFile("reposition"); if (saveFile == null) { return; } // do the resample using (var reader = new MediaFoundationReader(InputFile)) using (var resampler = new MediaFoundationResampler(reader, CreateOutputFormat(reader.WaveFormat))) { CreateRepositionTestFile(saveFile, resampler, () => { // tell the reader to go back to the start (we're trusting it not to have leftovers) reader.Position = 0; // tell the resampler that we have repositioned and it should drain all its buffers resampler.Reposition(); }); } // use the following to test that just the reader is doing clean repositions: /* * using (var reader = new MediaFoundationReader(InputFile)) * { * CreateRepositionTestFile(saveFile, reader, () => * { * // tell the reader to go back to the start (we're trusting it not to have leftovers) * reader.Position = 0; * }); * }*/ MessageBox.Show("Resample complete"); }
public CachedSound(string audioFileName) { var newFileName = CachePath; try { int outRate = 44100; int channels = 2; var outFormat = new WaveFormat(outRate, channels); using (var audioFileReader = new MyAudioFileReader(audioFileName)) using (var resampler = new MediaFoundationResampler(audioFileReader, outFormat)) using (var stream = new FileStream(newFileName, FileMode.Create)) { resampler.ResamplerQuality = 60; WaveFileWriter.WriteWavFileToStream(stream, resampler); } } catch (Exception e) { Console.WriteLine(audioFileName); throw; } using (var audioFileReader = new AudioFileReader(newFileName)) { WaveFormat = audioFileReader.WaveFormat; var wholeFile = new List <float>((int)(audioFileReader.Length / 4)); var readBuffer = new float[audioFileReader.WaveFormat.SampleRate * audioFileReader.WaveFormat.Channels]; int samplesRead; while ((samplesRead = audioFileReader.Read(readBuffer, 0, readBuffer.Length)) > 0) { wholeFile.AddRange(readBuffer.Take(samplesRead)); } AudioData = wholeFile.ToArray(); Duration = audioFileReader.TotalTime.Milliseconds; } }
/// <summary> /// 渲染音乐 /// </summary> /// <param name="outFile">输出文件</param> public void Render(string outFile) { int sleepTime = Convert.ToInt32((60.0 / Bpm) * 1000.0); byte[] buffer = new byte[1024]; var ms = new MemoryStream(); var rs = new RawSourceWaveStream(ms, new WaveFormat(16000, 16, 2)); List <ISampleProvider> resultSound = new List <ISampleProvider>(); int count = 1; foreach (var beat in Notes) { List <ISampleProvider> notesSound = new List <ISampleProvider>(); foreach (var note in beat.GetNotes()) { var _reader = new AudioFileReader(note.Instrument.GetFile(note.pName, note.Octive, note.Dynam)); _reader.Volume = note.Volume; var outFormat = new WaveFormat(44100, _reader.WaveFormat.Channels); var resampler = new MediaFoundationResampler(_reader, outFormat); var _trimmed = new OffsetSampleProvider(resampler.ToSampleProvider()) { Take = new TimeSpan(0, 0, 0, 0, sleepTime * note.Duration) }; notesSound.Add(_trimmed); } count++; if (notesSound.Count > 0) { var mixer = new MixingSampleProvider(notesSound); var trimmed = new OffsetSampleProvider(mixer) { DelayBy = TimeSpan.FromMilliseconds(count * sleepTime) }; resultSound.Add(trimmed); } } var ResultMixer = new MixingSampleProvider(resultSound); WaveFileWriter.CreateWaveFile16(outFile, ResultMixer); }
public static void convertToBrstm(string path) { using (var input = new WaveFileReader(path)) { if (input.WaveFormat.Encoding != WaveFormatEncoding.Pcm) { string temppath = "temp.wav"; var outFormat = new WaveFormat(input.WaveFormat.SampleRate, input.WaveFormat.Channels); using (var resampler = new MediaFoundationResampler(input, outFormat)) { // resampler.ResamplerQuality = 48; WaveFileWriter.CreateWaveFile(temppath, resampler); } } } if (File.Exists("temp.wav")) { File.Delete(path); File.Move("temp.wav", path); } WaveStructure structure; WaveReader reader = new WaveReader(); byte[] fs = File.ReadAllBytes(path); string newpath = new string(path.Take(path.Length - 3).ToArray()); newpath += "brstm"; handleExistingFile(newpath); Stream stream = new MemoryStream(fs); structure = reader.ReadMetadata(stream); AudioData audio = reader.Read(fs); audio.SetLoop(true, 0, structure.SampleCount); byte[] brstmFile = new BrstmWriter().GetFile(audio); File.WriteAllBytes(newpath, brstmFile); Console.WriteLine($"Converted: {path} \n --> {newpath}"); }
//添加字幕 //public static async Task<string> Addsrt(string videoPath, string srtPath) //{ // string outputPath = Path.ChangeExtension(Path.GetTempFileName(), ".mp4"); // IConversion conversion = await FFmpeg.Conversions.FromSnippet.AddSubtitle(videoPath,outputPath,srtPath); // //await Conversion.AddSubtitles(videoPath, outputPath, srtPath).Start(); // IConversionResult result = await conversion.Start(); // return outputPath; //} //音频混合 static public void MixBgmAndSpeech(Info info) { float bgmVolume = info.BgmVolume; float speechVolume = info.PersonVolume; string bgmFilePath = info.AudioPath; string speechFilePath = info.speechTemp; string tempPath1 = Path.ChangeExtension(Path.GetTempFileName(), ".wav"); string tempPath2 = Path.ChangeExtension(Path.GetTempFileName(), ".wav"); //string outputFilePath = Path.ChangeExtension(Path.GetTempFileName(), ".wav"); string audio1FilePath = tempPath1; string audio2FilePath = tempPath2; using (var bgmReader = new AudioFileReader(bgmFilePath)) using (var speechReader = new AudioFileReader(speechFilePath)) { using (var resampler = new MediaFoundationResampler(speechReader, bgmReader.WaveFormat)) { WaveFileWriter.CreateWaveFile(audio2FilePath, resampler); audio1FilePath = bgmFilePath; } } //混音 using (var reader1 = new AudioFileReader(audio1FilePath)) using (var reader2 = new AudioFileReader(audio2FilePath)) { reader1.Volume = bgmVolume; reader2.Volume = speechVolume; var mixer = new MixingSampleProvider(new[] { reader1, reader2 }); WaveFileWriter.CreateWaveFile16(info.mixed, mixer); } //删除临时文件 if (File.Exists(tempPath1)) { File.Delete(tempPath1); } if (File.Exists(tempPath2)) { File.Delete(tempPath2); } }
private void Resample() { if (String.IsNullOrEmpty(InputFile)) { MessageBox.Show("Select a file first"); return; } var saveFile = SelectSaveFile("resampled"); if (saveFile == null) { return; } // do the resample using (var reader = new MediaFoundationReader(InputFile)) using (var resampler = new MediaFoundationResampler(reader, CreateOutputFormat(reader.WaveFormat))) { WaveFileWriter.CreateWaveFile(saveFile, resampler); } MessageBox.Show("Resample complete"); }
public static void Speak(string file, CommandEventArgs e) { try { if (!Program.isConnected) { InstantiateVoiceConnection(); } if (Program._vClient != null) { var channelCount = Program._client.GetService <AudioService>().Config.Channels; var OutFormat = new WaveFormat(48000, 16, channelCount); using (var MP3Reader = new Mp3FileReader(Definitions.ServerDefinitions.AudioPath.GetStringValue() + file + ".mp3")) using (var resampler = new MediaFoundationResampler(MP3Reader, OutFormat)) { resampler.ResamplerQuality = 60; int blockSize = OutFormat.AverageBytesPerSecond / 50; byte[] buffer = new byte[blockSize]; int byteCount; while ((byteCount = resampler.Read(buffer, 0, blockSize)) > 0) { if (byteCount < blockSize) { for (int i = byteCount; i < blockSize; i++) { buffer[i] = 0; } } Program._vClient.Send(buffer, 0, blockSize); } } } } catch (FileNotFoundException) { Common.GetTextChannel(Definitions.TextChannels.ChatNChill.GetStringValue()).SendTTSMessage("That file wasn't found."); } }
/// <summary> /// Creates Sample provider for cached AudioData. /// </summary> /// <param name="audioData">Audio data.</param> /// <param name="playbackToken">Playback token.</param> /// <param name="masterVolumeProvider">Master volume provider.</param> /// <param name="volume">Volume for audio playback.</param> /// <param name="useParallel">true if use parallel.</param> public AudioDataFileSampleProvider(AudioData audioData, PlaybackToken playbackToken, IMasterVolumeProvider masterVolumeProvider, float volume = 1.0f, bool useParallel = false) : base(audioData, playbackToken, masterVolumeProvider, volume, useParallel) { string filePath = audioData.FilePath; if (filePath != null) { this.reader = new AudioFileReader(filePath); this.isAudioFileReaderDisposed = false; this.resampler = AudioData.CreateResampler(this.reader, audioData.WaveFormat, audioData.ResamplingQuality); if (this.resampler != null) { this.stream = resampler.ToSampleProvider(); } else { this.stream = reader; } } }
public AudioConvert() { ComputerCraftStuff CCS = new ComputerCraftStuff(); string file = "./data/banana.wav"; string outfile = "./data/pang.dfpwm"; var raw = new MediaFoundationReader(file); var outFormat = new WaveFormat(48000, 8, 1); var reader = new MediaFoundationResampler(raw, outFormat); List <byte> outFile = new List <byte>(); byte[] readBuffer = new byte[1024]; byte[] outBuffer = new byte[readBuffer.Length / 8]; int read; do { for (read = 0; read < readBuffer.Length;) { int amt = reader.Read(readBuffer, read, readBuffer.Length - read); if (amt == 0) { break; } read += amt; } read &= ~0x07; CCS.AudioCompress(outBuffer, readBuffer, 0, 0, read / 8); outFile.AddRange(outBuffer); } while (read == readBuffer.Length); File.WriteAllBytes(outfile, outFile.ToArray()); }
protected Stream SerialAudioEncode() { var mem = new MemoryStream(); try { using (var writer = new BinaryWriter(mem, Encoding.Unicode, true)) using (var wav = new WaveFileReader(basesource.GetStream())) using (var res = new MediaFoundationResampler(wav, new WaveFormat( wav.WaveFormat.SampleRate < 32000 ? 24000 : 48000 , 1))) { var opus = OpusEncoder.Create(res.WaveFormat.SampleRate, 1, FragLabs.Audio.Codecs.Opus.Application.Voip); opus.Bitrate = 96000; int packetsize = (int)(res.WaveFormat.SampleRate * 0.04); byte[] buffer = new byte[packetsize]; int result = res.Read(buffer, 0, packetsize); while (result > 0) { int outlen = 0; byte[] output = opus.Encode(buffer, result / 2, out outlen); writer.Write((uint)outlen); writer.Write(output, 0, outlen); result = res.Read(buffer, 0, packetsize); } } } catch (Exception ex) { } finally { mem.Position = 0; _size = (uint)mem.Length; } return(mem); }
private void Start() { //Store when we first start trying to start if (!_firstStartAttemptUtc.HasValue) { _firstStartAttemptUtc = DateTime.UtcNow; } //Check for timeout if (DateTime.UtcNow - _firstStartAttemptUtc.Value > TimeSpan.FromSeconds(15)) { IsComplete = true; } //Exit out if the clip isn't ready yet if (!Clip.Clip.IsLoaded) { return; } var format = new WaveFormat(48000, 16, 2); var s = Clip.Clip.Open(); _source = s as IDisposable; _resampler = new MediaFoundationResampler(s.ToWaveProvider(), format) { ResamplerQuality = 60 }; // Copy the data in ~200ms blocks var blockSize = format.AverageBytesPerSecond / 50; _buffer = new byte[blockSize]; _started = true; }
public static async Task SendAudio(string filepath, Channel voiceChannel) { vClient = await discord.GetService <AudioService>().Join(voiceChannel); try { var channelCount = discord.GetService <AudioService>().Config.Channels; // Get the number of AudioChannels our AudioService has been configured to use. var OutFormat = new WaveFormat(48000, 16, channelCount); // Create a new Output Format, using the spec that Discord will accept, and with the number of channels that our client supports. using (var WaveReader = new WaveFileReader(filepath)) // Create a new Disposable MP3FileReader, to read audio from the filePath parameter using (var resampler = new MediaFoundationResampler(WaveReader, OutFormat)) // Create a Disposable Resampler, which will convert the read MP3 data to PCM, using our Output Format { resampler.ResamplerQuality = 60; // Set the quality of the resampler to 60, the highest quality int blockSize = OutFormat.AverageBytesPerSecond / 50; // Establish the size of our AudioBuffer byte[] buffer = new byte[blockSize]; int byteCount; while ((byteCount = resampler.Read(buffer, 0, blockSize)) > 0 && playingSong) // Read audio into our buffer, and keep a loop open while data is present { if (byteCount < blockSize) { // Incomplete Frame for (int i = byteCount; i < blockSize; i++) { buffer[i] = 0; } } vClient.Send(buffer, 0, blockSize); // Send the buffer to Discord } await vClient.Disconnect(); } } catch { //if something goes wrong. System.Console.WriteLine("lol oops"); } await vClient.Disconnect(); }
public void Start() { try { Capturer = new WasapiLoopbackCapture(); TargetFormat = new WaveFormat(16000, 8, 1); Capturer.DataAvailable += async(aud, args) => { try { if (args.BytesRecorded > 0) { using (var ms1 = new MemoryStream()) { using (var wfw = new WaveFileWriter(ms1, Capturer.WaveFormat)) { wfw.Write(args.Buffer, 0, args.BytesRecorded); } // Resample to 16-bit so Firefox will play it. using (var ms2 = new MemoryStream(ms1.ToArray())) using (var wfr = new WaveFileReader(ms2)) using (var ms3 = new MemoryStream()) { using (var resampler = new MediaFoundationResampler(wfr, TargetFormat)) { WaveFileWriter.WriteWavFileToStream(ms3, resampler); } await Conductor.CasterSocket.SendAudioSample(ms3.ToArray(), Conductor.Viewers.Keys.ToList()); } } } } catch { } }; Capturer.StartRecording(); } catch { } }
/// <summary> /// Mixes two mp3 files to a single wav file. /// </summary> public void mixMp3() { Mp3FileReader reader1 = new Mp3FileReader(file1); Mp3FileReader reader2 = new Mp3FileReader(file2); int maxSampleRate = Math.Max(reader1.WaveFormat.SampleRate, reader2.WaveFormat.SampleRate); WaveFormat format = new WaveFormat(maxSampleRate, 1); MediaFoundationResampler resampler1 = new MediaFoundationResampler(reader1, format); var input1 = resampler1.ToSampleProvider(); MediaFoundationResampler resampler2 = new MediaFoundationResampler(reader2, format); var input2 = resampler2.ToSampleProvider(); ISampleProvider[] provider = { input1, input2 }; MixingSampleProvider mixer = new MixingSampleProvider(provider); WaveFileWriter.CreateWaveFile16(mixfile, mixer); resampler1.Dispose(); resampler2.Dispose(); reader1.Close(); reader1.Dispose(); reader2.Close(); reader2.Dispose(); }
public void Convert(Stream inputOgg, Stream outputWav) { using MemoryStream pcmStream = new(); OpusDecoder decoder = OpusDecoder.Create(INPUT_FREQUENCY, CHANNELS); OpusOggReadStream oggReader = new OpusOggReadStream(decoder, inputOgg); while (oggReader.HasNextPacket) { short[] packet = oggReader.DecodeNextPacket(); if (packet != null) { for (int i = 0; i < packet.Length; i++) { var bytes = BitConverter.GetBytes(packet[i]); pcmStream.Write(bytes, 0, bytes.Length); } } } pcmStream.Position = 0; using var wavStream = new RawSourceWaveStream(pcmStream, new WaveFormat(INPUT_FREQUENCY, CHANNELS)); using var resampler = new MediaFoundationResampler(wavStream, new WaveFormat(OUTPUT_FREQUENCY, CHANNELS)); WaveFileWriter.WriteWavFileToStream(outputWav, resampler); }
/// <summary> /// 音声データを読み込みます /// </summary> /// <param name="filename">ファイル名</param> /// <returns>読み込んだデータをdouble[](-1.0~1.0)に変換したもの</returns> public double[] Read(string filename) { Data = null; Format = new WaveFormat(48000, 16, 1); string tmpFile = "resampled.wav"; using (WaveFileReader reader = new WaveFileReader(filename)) { using (var resampler = new MediaFoundationResampler(reader, Format)) { WaveFileWriter.CreateWaveFile(tmpFile, resampler); } } using (WaveFileReader reader = new WaveFileReader(tmpFile)) { byte[] src = new byte[reader.Length]; reader.Read(src, 0, src.Length); Data = ConvertToDouble(src); } return(Data); }
public static void Play(Music MusicToPlay) { int channelCount = Program._client.GetService <AudioService>().Config.Channels; // Get the number of AudioChannels our AudioService has been configured to use. WaveFormat OutFormat = new WaveFormat(SampleRate, 16, channelCount); // Create a new Output Format, using the spec that Discord will accept, and with the number of channels that our client supports. try { mediaStream = new WaveChannel32(new MediaFoundationReader(MusicToPlay.FilePath), Volume, 0F); using (mediaStream) using (resampler = new MediaFoundationResampler(mediaStream, OutFormat)) // Create a Disposable Resampler, which will convert the read MP3 data to PCM, using our Output Format { resampler.ResamplerQuality = 60; // Set the quality of the resampler to 60, the highest quality int blockSize = OutFormat.AverageBytesPerSecond / 50; // Establish the size of our AudioBuffer byte[] buffer = new byte[blockSize]; int byteCount; while ((byteCount = resampler.Read(buffer, 0, blockSize)) > 0) // Read audio into our buffer, and keep a loop open while data is present { if (byteCount < blockSize) { // Incomplete Frame for (int i = byteCount; i < blockSize; i++) { buffer[i] = 0; } } _vClient.Send(buffer, 0, blockSize); // Send the buffer to Discord } } } catch (Exception ReaderException) { Console.WriteLine(ReaderException.Message); // Prints any errors to console } _vClient.Wait(); // Waits for the currently playing sound file to end. }
internal AudioTrack(string filename, MixingSampleProvider mixer) { using (var reader = new AudioFileReader(filename)) { //if the mixer and file wave formats do not match, re-sample if (!reader.WaveFormat.AreFormatsEqual(mixer.WaveFormat)) { //re-sample the audio to match the mixer wave format using (var sampler = new MediaFoundationResampler(reader, mixer.WaveFormat)) { using (var memory = new MemoryStream()) { WaveFileWriter.WriteWavFileToStream(memory, sampler); AudioData = memory.GetBuffer(); } } } else { //no need to re-sample var data = new byte[reader.Length]; reader.Read(data, 0, (int)reader.Length); AudioData = data; } //set a default multipart loop MultipartLoop = new MultipartLoop(reader.CurrentTime, reader.TotalTime); } Mixer = mixer; Mixer.MixerInputEnded += MixerInputEnded; }
public CachedSound(string audioFileName) { using (var audioFileReader = new AudioFileReader(audioFileName)) { // TODO: could add resampling in here if required MediaFoundationResampler resampler = new MediaFoundationResampler(audioFileReader.ToWaveProvider(), 44100); WaveFormat = resampler.WaveFormat; var wholeFile = new List <float>((int)(audioFileReader.Length / 4)); var readBuffer = new byte[resampler.WaveFormat.SampleRate * resampler.WaveFormat.Channels]; int samplesRead; while ((samplesRead = resampler.Read(readBuffer, 0, readBuffer.Length)) > 0) { var tempByteArray = readBuffer.Take(samplesRead).ToArray(); var tempfloatarray = new float[tempByteArray.Count() / 4]; Buffer.BlockCopy(tempByteArray, 0, tempfloatarray, 0, tempByteArray.Count()); wholeFile.AddRange(tempfloatarray); } AudioData = wholeFile.ToArray(); } }
private void SendTempBuffer() { if (TempBuffer.Count == 0) { return; } using var ms1 = new MemoryStream(); using (var wfw = new WaveFileWriter(ms1, Capturer.WaveFormat)) { wfw.Write(TempBuffer.ToArray(), 0, TempBuffer.Count); } TempBuffer.Clear(); // Resample to 16-bit so Firefox will play it. using var ms2 = new MemoryStream(ms1.ToArray()); using var wfr = new WaveFileReader(ms2); using var ms3 = new MemoryStream(); using (var resampler = new MediaFoundationResampler(wfr, TargetFormat)) { WaveFileWriter.WriteWavFileToStream(ms3, resampler); } AudioSampleReady?.Invoke(this, ms3.ToArray()); }
/// <summary> /// Class constructor. /// </summary> public CachedSound(string file, int sampleRate, int channels, float volume = 1.0f) { using (AudioFileReader reader = new AudioFileReader(file)) { reader.Volume = volume; if ((reader.WaveFormat.SampleRate == sampleRate) && (reader.WaveFormat.Channels == channels)) { List <float> wholeFile = new List <float>((int)(reader.Length / 4)); float[] buffer = new float[reader.WaveFormat.SampleRate * reader.WaveFormat.Channels]; int samplesRead; while ((samplesRead = reader.Read(buffer, 0, buffer.Length)) > 0) { wholeFile.AddRange(buffer.Take(samplesRead)); } AudioData = wholeFile.ToArray(); WaveFormat = reader.WaveFormat; } else { WaveFormat newFormat = new WaveFormat(sampleRate, channels); using (MediaFoundationResampler resampler = new MediaFoundationResampler(reader, newFormat)) { ISampleProvider sampleProvider = resampler.ToSampleProvider(); List <float> wholeFile = new List <float>(); float[] buffer = new float[newFormat.SampleRate * newFormat.Channels]; int samplesRead; while ((samplesRead = sampleProvider.Read(buffer, 0, buffer.Length)) > 0) { wholeFile.AddRange(buffer.Take(samplesRead)); } AudioData = wholeFile.ToArray(); WaveFormat = newFormat; } } } }
private float[] ReadMonoFromSource(string pathToSource, int sampleRate, int secondsToRead, int startAtSecond, Func<SampleProviderConverterBase, ISamplesProvider> getSamplesProvider) { using (var reader = new MediaFoundationReader(pathToSource)) { SeekToSecondInCaseIfRequired(startAtSecond, reader); var ieeeFloatWaveFormat = WaveFormat.CreateIeeeFloatWaveFormat(sampleRate, 1); using (var resampler = new MediaFoundationResampler(reader, ieeeFloatWaveFormat)) { var waveToSampleProvider = new WaveToSampleProvider(resampler); return samplesAggregator.ReadSamplesFromSource(getSamplesProvider(waveToSampleProvider), secondsToRead, sampleRate); } } }
public void Play( string file, float volume = 1.0f, bool sync = false) { if (!File.Exists(file)) { return; } var buffer = default(BufferedWaveProvider); if (!sync) { lock (this) { buffer = this.Buffers[this.CurrentPlayerIndex]; this.CurrentPlayerIndex++; if (this.CurrentPlayerIndex >= MultiplePlaybackCount) { this.CurrentPlayerIndex = 0; } } } else { buffer = this.Buffers[MultiplePlaybackCount]; } if (buffer == null) { return; } var samples = default(byte[]); var key = $"{file}-{volume}"; lock (WaveBuffer) { if (WaveBuffer.ContainsKey(key)) { samples = WaveBuffer[key]; } else { var vol = volume > 1.0f ? 1.0f : volume; using (var audio = new AudioFileReader(file) { Volume = vol }) using (var resampler = new MediaFoundationResampler(audio, this.OutputFormat)) using (var output = new MemoryStream(51200)) { WaveFileWriter.WriteWavFileToStream(output, resampler); output.Flush(); output.Position = 0; // ヘッダをカットする var raw = output.ToArray(); var headerLength = 0; using (var wave = new WaveFileReader(output)) { headerLength = (int)(raw.Length - wave.Length); } // ヘッダをスキップした波形データを取得する samples = raw.Skip(headerLength).ToArray(); } WaveBuffer[key] = samples; } } buffer.AddSamples( samples, 0, samples.Length); #if DEBUG System.Diagnostics.Debug.WriteLine($"WASAPI(Buffered) Play: {file}"); #endif }
public void RecodeFileToMonoWave(string pathToFile, string outputPathToFile, int targetSampleRate) { using (Mp3FileReader reader = new Mp3FileReader(pathToFile)) { using (var resampler = new MediaFoundationResampler(reader, WaveFormat.CreateIeeeFloatWaveFormat(targetSampleRate, 1))) { WaveFileWriter.CreateWaveFile(outputPathToFile, resampler); } } }
public static void StartNewTrack() { // find out what to play var tracks = FindTracks().ToArray(); var track = tracks.Where(t => t.Mood == CurrentMood).PickRandom(); if (track == null) { // no music? try another mood var others = tracks; if (others.Any()) { track = others.PickRandom(); } } if (track == null) { // no music at all :( return; } // prepare the new track var tl = track.Path.ToLower(); WaveChannel32 wc = null; if (tl.EndsWith("ogg")) { wc = new WaveChannel32(new VorbisWaveReader(track.Path)); } else if (tl.EndsWith("mp3")) { wc = new WaveChannel32(new Mp3FileReader(track.Path)); } else if (tl.EndsWith("wav")) { wc = new WaveChannel32(new WaveFileReader(track.Path)); } else { throw new Exception("Unknown audio format for file " + track.Path); } // convert to a standard format so we can mix them (e.g. a mp3 with an ogg) var resampler = new MediaFoundationResampler(wc, waveFormat); var sp = resampler.ToSampleProvider(); // setup our track wc.Volume = musicVolume; wc.PadWithZeroes = false; // to allow PlaybackStopped event to fire // fade between the two tracks mixer.RemoveMixerInput(prevTrack); prevTrack = curTrack; if (prevTrack != null) { prevTrack.BeginFadeOut(FadeDuration); } curTrack = new FadeInOutSampleProvider(sp, true); curTrack.BeginFadeIn(FadeDuration); mixer.AddMixerInput(curTrack); waveout.Play(); IsPlaying = true; }
public void RecodeFileToMonoWave(string pathToFile, string pathToRecodedFile, int sampleRate) { using (var reader = new MediaFoundationReader(pathToFile)) { var ieeeFloatWaveFormat = WaveFormat.CreateIeeeFloatWaveFormat(sampleRate, 1); using (var resampler = new MediaFoundationResampler(reader, ieeeFloatWaveFormat)) { WaveFileWriter.CreateWaveFile(pathToRecodedFile, resampler); } } }