public void sendAudio() { discord._client.SetGame(currentSongText); Console.WriteLine("Setting game to " + currentSongText); var channelCount = discord._client.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(musicToPlay)) // 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; } buffer = adjustVolume(buffer, volume); try { discord._vClient.Send(buffer, 0, blockSize); // Send the buffer to Discord } catch (Exception ex1) { } } Console.WriteLine("Song done"); // discord._client.SetGame(""); discord._client.SetGame(new Game()); if (!playingFolders && !nextSongText.Equals("null") && !nextSongText.Equals(currentSongText)) { Console.WriteLine("meow"); currentSongText = nextSongText; nextSongText = "null"; //update(); sendAudio(); } else if (playingFolders) { if (folderFiles.Count > 0) { Random rdm = new Random(); int choice = rdm.Next(0, folderFiles.Count); musicToPlay = folderFiles.ElementAt(choice); currentSongText = System.IO.Path.GetFileName(musicToPlay); nextSongText = "null"; //update(); folderFiles.RemoveAt(choice); sendAudio(); } else { Console.WriteLine("Queue complete"); } } } }
/// <summary> /// Creates a resampler with a specified target output sample rate /// </summary> /// <param name="sourceProvider">Source provider</param> /// <param name="outputSampleRate">Output sample rate</param> // Token: 0x06000A61 RID: 2657 RVA: 0x0001E42C File Offset: 0x0001C62C public MediaFoundationResampler(IWaveProvider sourceProvider, int outputSampleRate) : this(sourceProvider, MediaFoundationResampler.CreateOutputFormat(sourceProvider.WaveFormat, outputSampleRate)) { }
private async Task RequestCommand(CommandEventArgs e) { var urlToDownload = e.Args[0]; var newFilename = Guid.NewGuid().ToString(); var mp3OutputFolder = @"c:\mp3\"; if (urlToDownload.Contains("soundcloud")) { Track track = _soundCloud.GetTrack(e.Args[0]); string inPath = Path.Combine(mp3OutputFolder, newFilename + ".mp3"); if (!track.Streamable) { await e.Channel.SendMessage("\"" + track.Title + "\" is not streamable :C"); } try { using (var client = new WebClient()) { client.DownloadFile(track.StreamUrl + "?client_id=" + _soundCloud.ClientID, inPath); } } catch (Exception ex) { Console.Write(ex.ToString()); } var outFile = inPath.Remove(inPath.Length - 4) + "_c" + ".wav"; try { using (var reader = new MediaFoundationReader(inPath)) { var outFormat = new WaveFormat(48000, 16, 2); using (var resampler = new MediaFoundationResampler(reader, outFormat)) { resampler.ResamplerQuality = 60; VolumeWaveProvider16 vol = new VolumeWaveProvider16(resampler); vol.Volume = 0.3f; WaveFileWriter.CreateWaveFile(outFile, vol); } } File.Delete(inPath); } catch (Exception e2) { Console.Write(e2.ToString()); return; } await e.Channel.SendMessage("Added \"" + track.Title + "\" to the queue. It will be played soon."); _queue.musicQueue.Enqueue(Tuple.Create<string, string>(outFile, track.Title)); Thread thread = new Thread(() => { _queue.PlayNextMusicToAllVoiceClients(); }); thread.Start(); } else { IEnumerable<VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(e.Args[0]); VideoInfo video = videoInfos.Where(info => info.CanExtractAudio).OrderByDescending(info => info.AudioBitrate).First(); if (video.RequiresDecryption) { DownloadUrlResolver.DecryptDownloadUrl(video); } string inPath = Path.Combine(mp3OutputFolder, newFilename + video.AudioExtension); try { var audioDownloader = new AudioDownloader(video, inPath); audioDownloader.Execute(); } catch (Exception ex) { Console.WriteLine("Error while trying to download youtube link."); Console.Write(ex.ToString()); } var outFile = inPath.Remove(inPath.Length - 4) + "_c" + ".wav"; try { using (var reader = new MediaFoundationReader(inPath)) { var outFormat = new WaveFormat(48000, 16, 2); using (var resampler = new MediaFoundationResampler(reader, outFormat)) { resampler.ResamplerQuality = 60; VolumeWaveProvider16 vol = new VolumeWaveProvider16(resampler); vol.Volume = 0.3f; WaveFileWriter.CreateWaveFile(outFile, vol); } } File.Delete(inPath); } catch (Exception e2) { Console.Write(e2.ToString()); return; } await e.Channel.SendMessage("Added \"" + video.Title + "\" to the queue. It will be played soon."); _queue.musicQueue.Enqueue(Tuple.Create<string, string>(outFile, video.Title)); Thread thread = new Thread(() => { _queue.PlayNextMusicToAllVoiceClients(); }); thread.Start(); } }
private void TestRheaStream() { DiscordVoiceClient vc = client.GetVoiceClient(); try { int ms = voiceMsBuffer; int channels = 1; int sampleRate = 48000; int blockSize = 48 * 2 * channels * ms; //sample rate * 2 * channels * milliseconds byte[] buffer = new byte[blockSize]; var outFormat = new WaveFormat(sampleRate, 16, channels); vc.SetSpeaking(true); using (var mp3Reader = new MediaFoundationReader("http://radiosidewinder.out.airtime.pro:8000/radiosidewinder_a")) { using (var resampler = new MediaFoundationResampler(mp3Reader, outFormat) { ResamplerQuality = 60 }) { int byteCount; while ((byteCount = resampler.Read(buffer, 0, blockSize)) > 0) { if (vc.Connected) { vc.SendVoice(buffer); } else break; } Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Voice finished enqueuing"); Console.ForegroundColor = ConsoleColor.White; resampler.Dispose(); mp3Reader.Close(); } } } catch(Exception ex) { owner.SendMessage("Exception during voice: `" + ex.Message + "`\n\n```" + ex.StackTrace + "\n```"); } }
// // Export button // private void exportToolStripMenuItem1_Click(object sender, EventArgs e) { //Debugs On the table deleteTempFilesToolStripMenuItem.Enabled = false; //mic stop if (sourceStream != null) { sourceStream.StopRecording(); sourceStream.Dispose(); } else if (waveWriter != null) { waveWriter.Dispose(); waveWriter = null; } //loopback stop else if (gravae != null) { gravae.StopRecording(); gravae.Dispose(); } else if (wri != null) { wri.Dispose(); wri = null; } if (File.Exists(@"C:\Windows\Temp\outputTemp.wav")) { File.Delete(@"C:\Windows\Temp\outputTemp.wav"); } if (File.Exists(@"C:\Windows\Temp\output4Chanels.wav")) { // //Muda o channel do output // int outRate = 44100; var inFile = @"C:\Windows\Temp\output4Chanels.wav"; var outFile = @"C:\Windows\Temp\outputTemp.wav"; using (var reader = new WaveFileReader(inFile)) { var outFormat = new WaveFormat(outRate, 2); using (var resampler = new MediaFoundationResampler(reader, outFormat)) { resampler.ResamplerQuality = 60; WaveFileWriter.CreateWaveFile(outFile, resampler); } } // //Mixa as Stream microphone e loopBack // foreach (WavePlayer clip in Clips) { clip.Dispose(); } Clips.Clear(); foreach (string file in files) { Clips.Add(new WavePlayer(file)); } var mixer = new MixingWaveProvider32(Clips.Select(c => c.Channel)); SaveFileDialog save = new SaveFileDialog(); save.Filter = "Mp3 Files (*.mp3)|*.mp3"; if (save.ShowDialog() != DialogResult.OK) return; this.UseWaitCursor = true; MediaFoundationEncoder.EncodeToMp3(mixer, save.FileName, 128); MessageBox.Show("Export High Light Done!"); this.UseWaitCursor = false; } }
protected static void ConvertToWav(PhraseItem item, string folder, bool play, string [] details) { //Engine Name, SelectedVoice.Name, SelectedDiscreteSpeed, SelectedDiscreteVolume try { TagLib.File file = TagLib.File.Create(String.Format("{0}\\mp3\\{1}\\{2}.mp3", folder, item.Folder, item.FileName)); file.Tag.Title = item.Phrase; file.Tag.Comment = String.Format("{0}, {1}, {2}, {3}", details[0], details[1], details[2], details[3]); file.Save(); } catch { } if (Properties.Settings.Default.EncodeToWav == true) { using (Mp3FileReader mp3 = new Mp3FileReader(String.Format("{0}\\mp3\\{1}\\{2}.mp3", folder, item.Folder, item.FileName))) { using (var resampler = new MediaFoundationResampler(mp3, new NAudio.Wave.WaveFormat(Properties.Settings.Default.WavSampleRate, Properties.Settings.Default.WavBitsPerSample, 1))) { resampler.ResamplerQuality = 60; WaveFileWriter.CreateWaveFile(String.Format("{0}\\wav\\{1}\\{2}.wav", folder, item.Folder, item.FileName), resampler); } } } if (play) { MainWindow.PlayAudioFullPath(String.Format("{0}\\{3}\\{1}\\{2}.{3}", folder, item.Folder, item.FileName, Properties.Settings.Default.EncodeToWav? "wav":"mp3")); } item.DownloadComplete = true; }
private void StartPlay() { try { var outFormat = new WaveFormat(48000, 16, 2); using (var resampler = new MediaFoundationResampler(bufferedWaveProvider, outFormat)) { resampler.ResamplerQuality = 60; int blocksize = resampler.WaveFormat.AverageBytesPerSecond / 5; byte[] buffer = new byte[blocksize]; VolumeWaveProvider16 vol = new VolumeWaveProvider16(resampler); vol.Volume = 0.3f; while (bufferedWaveProvider.BufferedBytes > bufferedWaveProvider.WaveFormat.AverageBytesPerSecond / 5 && playbackState != StreamingPlaybackState.Stopped) { vol.Read(buffer, 0, blocksize); _client.Send(buffer, 0, blocksize); _client.Wait(); } } } catch (Exception e2) { Console.Write(e2.ToString()); return; } if(playbackState != StreamingPlaybackState.Stopped) playbackState = StreamingPlaybackState.Buffering; Console.WriteLine(String.Format("Gotta buffer")); }
private static void VoiceStuffs(DiscordVoiceClient vc, string file) { try { int ms = 60; int channels = 1; int sampleRate = 48000; int blockSize = 48 * 2 * channels * ms; //sample rate * 2 * channels * milliseconds byte[] buffer = new byte[blockSize]; var outFormat = new WaveFormat(sampleRate, 16, channels); vc.SetSpeaking(true); using (var mp3Reader = new MediaFoundationReader(file)) { using (var resampler = new MediaFoundationResampler(mp3Reader, outFormat) { ResamplerQuality = 60 }) { //resampler.ResamplerQuality = 60; int byteCount; while ((byteCount = resampler.Read(buffer, 0, blockSize)) > 0) { if (vc.Connected) { vc.SendVoice(buffer); } else break; } Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Voice finished enqueuing"); Console.ForegroundColor = ConsoleColor.White; } } } catch (Exception ex) { owner.SendMessage("Exception during voice: `" + ex.Message + "`\n\n```" + ex.StackTrace + "\n```"); } }
public static void SendAudio(string filePath) { 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 } } _vClient.Disconnect(); }
public async Task<string> EncodeMp3(string pathToMp3) { //WaveOut waveOutDev = new WaveOut(); Mp3FileReader m = new Mp3FileReader(pathToMp3); VoiceDebugLogger.Log($"Loading MP3 file {pathToMp3}"); var outFormat = new WaveFormat(480000, 16, 2); using (var resampler = new MediaFoundationResampler(m, outFormat)) { resampler.ResamplerQuality = 60; await Task.Run(()=>WaveFileWriter.CreateWaveFile("a.wav", m)).ConfigureAwait(false); return "a.wav"; } }
private static ISampleProvider ReadWaveFile(WaveFileReader reader, CompositeDisposable disposables) { disposables.Add(reader); // if resampling is needed, do it. if (reader.WaveFormat.SampleRate != SampleRate) { var resampler = new MediaFoundationResampler(reader, WaveFormat.CreateIeeeFloatWaveFormat(SampleRate, ChannelCount)); disposables.Add(resampler); return resampler.ToSampleProvider(); } return reader.ToSampleProvider(); }
/// <summary> /// Converts the audio using the specified wave format. /// </summary> /// <param name="waveFormat">The WaveFormat to use for the conversion.</param> void ConvertWav(WaveFormat waveFormat) { reader.Position = 0; #if WINDOWS //var mediaTypes = MediaFoundationEncoder.GetOutputMediaTypes(NAudio.MediaFoundation.AudioSubtypes.MFAudioFormat_PCM); using (var resampler = new MediaFoundationResampler(reader, waveFormat)) { using (var outStream = new MemoryStream()) { // Since we cannot determine ahead of time the number of bytes to be // read, read four seconds worth at a time. byte[] bytes = new byte[reader.WaveFormat.AverageBytesPerSecond * 4]; while (true) { int bytesRead = resampler.Read(bytes, 0, bytes.Length); if (bytesRead == 0) break; outStream.Write(bytes, 0, bytesRead); } data = new List<byte>(outStream.ToArray()); format = new AudioFormat(waveFormat); } } #else throw new NotImplementedException(); #endif }
private async void PlayThread() { MediaFoundationResampler resamplerDmoStream = null; IWaveProvider playbackProvider = this.sourceProvider; Exception exception = null; try { if (this.resamplerNeeded) { resamplerDmoStream = new MediaFoundationResampler(sourceProvider, outputFormat); playbackProvider = resamplerDmoStream; } // fill a whole buffer bufferFrameCount = audioClient.BufferSize; bytesPerFrame = outputFormat.Channels*outputFormat.BitsPerSample/8; readBuffer = new byte[bufferFrameCount*bytesPerFrame]; FillBuffer(playbackProvider, bufferFrameCount); audioClient.Start(); while (playbackState != PlaybackState.Stopped) { // If using Event Sync, Wait for notification from AudioClient or Sleep half latency int timeout = 3*latencyMilliseconds; var r = NativeMethods.WaitForSingleObjectEx(frameEventWaitHandle, timeout, true); if (r != 0) throw new InvalidOperationException("Timed out waiting for event"); // If still playing and notification is ok if (playbackState == PlaybackState.Playing) { // See how much buffer space is available. int numFramesPadding = 0; // In exclusive mode, always ask the max = bufferFrameCount = audioClient.BufferSize numFramesPadding = (shareMode == AudioClientShareMode.Shared) ? audioClient.CurrentPadding : 0; int numFramesAvailable = bufferFrameCount - numFramesPadding; if (numFramesAvailable > 0) { FillBuffer(playbackProvider, numFramesAvailable); } } } // play the buffer out while (audioClient.CurrentPadding > 0) { await Task.Delay(latencyMilliseconds/2); } audioClient.Stop(); if (playbackState == PlaybackState.Stopped) { audioClient.Reset(); } } catch (Exception e) { exception = e; } finally { if (resamplerDmoStream != null) { resamplerDmoStream.Dispose(); } RaisePlaybackStopped(exception); } }
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"); }
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 void ProcessPP(ppParser pp) { for (int i = 0; i < pp.Subfiles.Count; i++) { IWriteFile iw = pp.Subfiles[i]; if (!iw.Name.EndsWith(".wav")) continue; Stream str = Tools.GetReadStream(iw); if (!str.CanSeek || str.Length == 0) { str.Close(); continue; } using (str) using (WaveFileReader wv = new WaveFileReader(str)) { if (wv.WaveFormat.Channels > 1 || wv.WaveFormat.SampleRate > SampleRate) // || wv.WaveFormat.Encoding != WaveFormatEncoding.Adpcm { WaveFormat f = new WaveFormat(SampleRate, 16, 1); //new AdpcmWaveFormat(wv.WaveFormat.SampleRate, 1); using (MediaFoundationResampler resampledAudio = new MediaFoundationResampler(wv, f)) { resampledAudio.ResamplerQuality = 60; MemoryStream o = new MemoryStream(); using (WaveFileWriter wr = new WaveFileWriter(o, f)) { int count = 0; byte[] buffer = new byte[2048]; while ((count = resampledAudio.Read(buffer, 0, 2048)) > 0) { wr.Write(buffer, 0, count); } wr.Flush(); pp.Subfiles[i] = new MemSubfile(ToByteArray(o), iw.Name); } } } } if (ProgressUpdated != null) ProgressUpdated((int)Math.Floor((double)(100 * i) / pp.Subfiles.Count)); } }
private void SendVoice(string file, DiscordClient client, YouTubeVideo video) { DiscordVoiceClient vc = client.GetVoiceClient(); try { int ms = vc.VoiceConfig.FrameLengthMs; int channels = vc.VoiceConfig.Channels; int sampleRate = 48000; int blockSize = 48 * 2 * channels * ms; //sample rate * 2 * channels * milliseconds byte[] buffer = new byte[blockSize]; var outFormat = new WaveFormat(sampleRate, 16, channels); vc.SetSpeaking(true); if(video.AudioFormat == AudioFormat.Mp3) { using (var mp3Reader = new Mp3FileReader(video.Stream())) { using (var resampler = new MediaFoundationResampler(mp3Reader, outFormat) { ResamplerQuality = 60 }) { //resampler.ResamplerQuality = 60; int byteCount; while ((byteCount = resampler.Read(buffer, 0, blockSize)) > 0) { if (vc.Connected) { vc.SendVoice(buffer); } else break; } Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Voice finished enqueuing"); Console.ForegroundColor = ConsoleColor.White; resampler.Dispose(); mp3Reader.Close(); } } } else if(video.AudioFormat == AudioFormat.Vorbis) { using (var vorbis = new NAudio.Vorbis.VorbisWaveReader(video.Stream())) { using (var resampler = new MediaFoundationResampler(vorbis, outFormat) { ResamplerQuality = 60 }) { int byteCount; while ((byteCount = resampler.Read(buffer, 0, blockSize)) > 0) { if (vc.Connected) { vc.SendVoice(buffer); } else break; } Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Voice finished enqueuing"); Console.ForegroundColor = ConsoleColor.White; resampler.Dispose(); vorbis.Close(); } } } } catch (Exception ex) { try { MainEntry.owner.SendMessage("Exception during voice: `" + ex.Message + "`\n\n```" + ex.StackTrace + "\n```"); } catch { } } }
private void Resample() { try { using (var reader = new WaveFileReader(Path.Combine(tempFolder, tempFilename))) { var outFormat = new WaveFormat(16000, reader.WaveFormat.Channels); using (var resampler = new MediaFoundationResampler(reader, outFormat)) { // resampler.ResamplerQuality = 60; WaveFileWriter.CreateWaveFile(Path.Combine(outputFolder, outputFileName), resampler); } } File.Delete(Path.Combine(tempFolder, tempFilename)); } catch (Exception exp) { Console.WriteLine(exp); } }