/// <summary> /// Mixes two wav files to a single wav file. (Unused). /// </summary> public void mix() { window.lockForMixing(); WaveFileReader reader1 = new WaveFileReader(file1); WaveFileReader reader2 = new WaveFileReader(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(); reader2.Close(); reader1.Dispose(); reader2.Dispose(); window.unlock(); }
private void HandleFile(string filename) { try { FileInfo file = new FileInfo(filename); string path = System.IO.Path.Combine(file.Directory.FullName, "output"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } AudioFileReader waveFileReader = new AudioFileReader(filename); int bytesPerMillisecond = waveFileReader.WaveFormat.AverageBytesPerSecond / 1000; int startPos = GetSilenceTime(waveFileReader, SilenceLocation.Start, config.Config.SilenceThreshold); int endPos2 = GetSilenceTime(waveFileReader, SilenceLocation.End, config.Config.SilenceThreshold); endPos2 -= endPos2 % 4; WaveFileWriter waveFileWriter = new WaveFileWriter(filename + ".temp.wav", waveFileReader.WaveFormat); TrimSound(waveFileReader, waveFileWriter, startPos, endPos2); byte[] temp = new byte[bytesPerMillisecond * 500]; waveFileWriter.Write(temp, 0, temp.Length); waveFileWriter.Close(); waveFileReader.Close(); WaveFileReader filereader = new WaveFileReader(filename + ".temp.wav"); WaveFormat format = new WaveFormat(8000, 16, 1); MediaFoundationResampler resample = new MediaFoundationResampler(filereader, format); WaveFileWriter.CreateWaveFile(System.IO.Path.Combine(path, file.Name.Replace(file.Extension, ".wav")), resample); resample.Dispose(); filereader.Close(); File.Delete(filename + ".temp.wav"); } catch (Exception) { } }
public override void Execute() { //WaveChannel32 WaveFloat = new WaveChannel32(new WaveFileReader(mSongPath)); MediaFoundationReader reader = new MediaFoundationReader(mSongPath); VolumeWaveProvider16 ww = new VolumeWaveProvider16(reader); if (ApplicationSettings.Volume != 100) { ww.Volume = (float)Math.Pow((ApplicationSettings.Volume / 100.0), 3); } var outFormat = new WaveFormat(22050, 16, 1); var resampler = new MediaFoundationResampler(ww, outFormat); resampler.ResamplerQuality = 60; string wavFileName = Path.Combine(CsGoLocationFinder.GetCsGoLocation(), ApplicationSettings.WavFileName); if (File.Exists(wavFileName)) { File.Delete(wavFileName); } WaveFileWriter.CreateWaveFile(wavFileName, resampler); resampler.Dispose(); Key.CsGoKeySender.SendCommands(CsComand); }
public void Dispose(ref string tex) { lock (mixOut) { if (startReading != null) { startReading.Dispose(); startReading = null; } } Logger.mix.a("dispose recCap"); tex = "recCap"; if (recCap != null) { recCap.StopRecording(); } Logger.mix.a("dispose micCap"); tex = "micCap"; if (micCap != null) { micCap.StopRecording(); } Logger.mix.a("dispose mixOut"); tex = "mixOut"; if (mixOut != null) { mixOut.Dispose(); } Logger.mix.a("dispose recRe"); tex = "recRe"; if (recRe != null) { recRe.Dispose(); } Logger.mix.a("dispose micRe"); tex = "micRe"; if (micRe != null) { micRe.Dispose(); } Logger.mix.a("disposed"); }
public void Dispose() { _source?.Dispose(); _source = null; _resampler?.Dispose(); _resampler = null; }
/// <summary> /// <inheritdoc cref="IDisposable.Dispose()"/> /// </summary> public void Dispose() { if (!_disposed) { _wasapiCapture?.Dispose(); _reSampler?.Dispose(); _disposed = true; } }
public static void TestRheaStream(DiscordMessageEventArgs e) { DiscordVoiceClient vc = client.GetVoiceClient(); if (vc == null) { SendBotMessage("!@Not in a channel!", e.Channel); } try { int ms = 20;//buffer 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("https://www.youtube.com/watch?v=2Vv-BfVoq4g")) { 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) { Log("Exception during voice: `" + ex.Message + "`\n\n```" + ex.StackTrace + "\n```", LogType.Console); } #endregion }
private void WaveCreator(string File, string outputFile, SourceGame Game) { MediaFoundationReader reader = new MediaFoundationReader(File); var outFormat = new WaveFormat(Game.Samplerate, Game.Bits, Game.Channels); var resampler = new MediaFoundationResampler(reader, outFormat); resampler.ResamplerQuality = 60; WaveFileWriter.CreateWaveFile(outputFile, resampler); resampler.Dispose(); }
protected override void OnDispose() { if (sampling_timer_ != null) { sampling_timer_.Dispose(); } if (reader_ != null) { reader_.Dispose(); } if (resampler_ != null) { resampler_.Dispose(); } }
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```"); } }
public void Dispose(ref string tex) { Logger.mix.a("dispose recCap"); tex = "recCap"; if (recCap != null) { recCap.StopRecording(); } Logger.mix.a("dispose micCap"); tex = "micCap"; if (micCap != null) { micCap.StopRecording(); } Logger.mix.a("dispose mixOut"); tex = "mixOut"; if (mixOut != null) { mixOut.Dispose(); } Logger.mix.a("dispose recRe"); tex = "recRe"; if (recRe != null) { recRe.Dispose(); } Logger.mix.a("dispose micRe"); tex = "micRe"; if (micRe != null) { micRe.Dispose(); } Logger.mix.a("disposed"); }
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 { } } }
public void Dispose() { WrappedAudioSource?.Dispose(); Resampler?.Dispose(); }
public void SendVoice(string file) { DiscordVoiceClient vc = Concordia.voice; 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); if (file.EndsWith(".wav")) { using (var waveReader = new WaveFileReader(file)) { int byteCount; while ((byteCount = waveReader.Read(buffer, 0, blockSize)) > 0) { if (vc.Connected) { vc.SendVoice(buffer); } else { break; } } } } else if (file.EndsWith(".mp3")) { 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; resampler.Dispose(); mp3Reader.Close(); } } } } catch (Exception ex) { Console.WriteLine("Exception during voice: `" + ex.Message + "`\n\n```" + ex.StackTrace + "\n```"); } }
public static async void PlayYouTube(string link, MessageEventArgs e) { IsPlaying = true; var vbot = await MusicCh.JoinAudio(); string BaseFilePath = System.AppDomain.CurrentDomain.BaseDirectory + @"Music\"; try { IEnumerable <VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(link); VideoInfo video = videoInfos .Where(info => info.CanExtractAudio) .OrderByDescending(info => info.AudioBitrate) .First(); if (video.RequiresDecryption) { DownloadUrlResolver.DecryptDownloadUrl(video); } MusicFileTitle = RemoveSpecialCharacters(video.Title) + video.AudioExtension; if (!File.Exists(BaseFilePath + MusicFileTitle)) { var audioDownloader = new AudioDownloader(video, Path.Combine(BaseFilePath, MusicFileTitle)); if (audioDownloader.BytesToDownload > 2000000 && !e.User.HasRole(Mod)) { e.User.SendMessage("The audio file is to large to download, try a shorter youtube video."); return; } try { System.Security.AccessControl.DirectorySecurity ds = Directory.GetAccessControl(BaseFilePath); } catch (UnauthorizedAccessException) { Console.WriteLine("Can not write to folder"); } try { audioDownloader.Execute(); } catch { e.User.SendMessage("Failed audioDownloader"); } } } catch (SystemException w) { await MusicCh.LeaveAudio(); await vbot.Disconnect(); IsPlaying = false; Console.WriteLine(w.Message); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed e.User.SendMessage(w.Message); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed } string filePath = BaseFilePath + MusicFileTitle; 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. if (!File.Exists(filePath)) { await MusicCh.LeaveAudio(); await vbot.Disconnect(); IsPlaying = false; return; } Playlist.Add(filePath); var MP3Reader = new Mp3FileReader(filePath); MP3Reader.Seek(0, SeekOrigin.Begin); 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 / 10; // Establish the size of our AudioBuffer byte[] buffer = new byte[blockSize]; int byteCount; while ((byteCount = resampler.Read(buffer, 0, blockSize)) > 0 && !ExitLoop) // 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; } } vbot.Send(buffer, 0, blockSize); // Send the buffer to Discord } resampler.Dispose(); vbot.Clear(); if (Playlist.Count() > 10) { DeletePlaylist(); } await vbot.Disconnect(); await MusicCh.LeaveAudio(); IsPlaying = false; }
private bool LoadTrack(SourceGame Game, int index) { Track Track = default(Track); if (Game.Tracks.Count > index) { Track = Game.Tracks[index]; string voicefile = Path.Combine(SteamAppsPath, Game.Directory) + "voice_input.wav"; try { if (File.Exists(voicefile)) { File.Delete(voicefile); } string trackfile = Game.Libraryname + Track.Name + Game.FileExtension; if (File.Exists(trackfile)) { if (Track.Volume == 100 & Track.Startpos == -1 & Track.Endpos == -1) { File.Copy(trackfile, voicefile); } else { WaveChannel32 WaveFloat = new WaveChannel32(new WaveFileReader(trackfile)); if (!(Track.Volume == 100)) { WaveFloat.Volume = (float)Math.Pow((Track.Volume / 100), 6); } if (!(Track.Startpos == Track.Endpos) & Track.Endpos > 0) { byte[] bytes = new byte[(Track.Endpos - Track.Startpos) * 4 + 1]; WaveFloat.Position = Track.Startpos * 4; WaveFloat.Read(bytes, 0, (Track.Endpos - Track.Startpos) * 4); WaveFloat = new WaveChannel32(new RawSourceWaveStream(new MemoryStream(bytes), WaveFloat.WaveFormat)); } WaveFloat.PadWithZeroes = false; var outFormat = new WaveFormat(Game.Samplerate, Game.Bits, Game.Channels); var resampler = new MediaFoundationResampler(WaveFloat, outFormat); resampler.ResamplerQuality = 60; WaveFileWriter.CreateWaveFile(voicefile, resampler); resampler.Dispose(); WaveFloat.Dispose(); } string GameCfgFolder = Path.Combine(SteamAppsPath, Game.Directory, Game.ToCfg); using (StreamWriter slam_curtrack = new StreamWriter(GameCfgFolder + "slam_curtrack.cfg")) { slam_curtrack.WriteLine("echo \"[SLAM] Track name: {0}\"", Track.Name); } using (StreamWriter slam_saycurtrack = new StreamWriter(GameCfgFolder + "slam_saycurtrack.cfg")) { slam_saycurtrack.WriteLine("say \"[SLAM] Track name: {0}\"", Track.Name); } using (StreamWriter slam_sayteamcurtrack = new StreamWriter(GameCfgFolder + "slam_sayteamcurtrack.cfg")) { slam_sayteamcurtrack.WriteLine("say_team \"[SLAM] Track name: {0}\"", Track.Name); } } } catch (Exception ex) { LogError(ex); return(false); } } else { return(false); } return(true); }
public void Stop() { mediaStream.Dispose(); resampler.Dispose(); }
public static async Task VoiceStream(VoiceNextConnection vnc, Video vid, int SpecialID) { MusicBot.ThreadIDD = SpecialID; MusicBot.UsersInChannel = DUtils.GetAmountInVoice(vnc.Channel); new Thread((ThreadStart)(() => vnc.VoiceReceived += (AsyncEventHandler <VoiceReceiveEventArgs>)(async e => { if (SpecialID != MusicBot.ThreadIDD) { Thread.CurrentThread.Abort(); } try { if (Config.StopPlayingIfANYsoundIsReceived) { MusicBot.StopPlayingJoined = true; } else { Utils.Debug((object)("Musicbot, Received sounds!!!" + e.User.Username)); } } catch (Exception ex) { if (Config.StopPlayingWithNewPlayer) { MusicBot.StopPlayingJoined = true; } if (!ex.Message.Contains("De objectverwijzing is niet op een exemplaar van een object ingesteld.") || !Config.StopPlayingWithNewPlayer) { return; } MusicBot.StopPlayingJoined = true; } await Task.Delay(1); }))).Start(); Exception exc = (Exception)null; string filename = MusicBot.CreatePathFromVid(MusicBot.FirstPlay()); if (!File.Exists(filename)) { Utils.Log(string.Format("File `{0}` does not exist.", (object)filename), LogType.Error); } else { Exception obj = null; int num = 0; try { try { int SampleRate = 48000; int channelCount = 2; WaveFormat OutFormat = new WaveFormat(SampleRate, 16, channelCount); MediaFoundationResampler resampler; WaveStream mediaStream; try { mediaStream = (WaveStream) new WaveChannel32((WaveStream) new MediaFoundationReader(filename), MusicBot.Volume, 0.0f); WaveStream waveStream = mediaStream; try { MediaFoundationResampler foundationResampler = resampler = new MediaFoundationResampler((IWaveProvider)mediaStream, OutFormat); try { int m = int.Parse(string.Concat((object)mediaStream.Length)); MusicBot.IntPlayout = m / 2 + m / 35; MusicBot.TotalSendBytes = 0; resampler.ResamplerQuality = 60; int blockSize = OutFormat.AverageBytesPerSecond / 50; byte[] buffer = new byte[blockSize]; do { int byteCount; if ((byteCount = resampler.Read(buffer, 0, blockSize)) > 0) { while (MusicBot.StopPlayingJoined) { Thread.Sleep(100); } if (byteCount < blockSize) { for (int i = byteCount; i < blockSize; ++i) { buffer[i] = (byte)0; } } MusicBot.TotalSendBytes += buffer.Length; Utils.Debug((object)("MusicBot, " + (object)MusicBot.TotalSendBytes + "/" + (object)MusicBot.IntPlayout)); if (SpecialID == MusicBot.ThreadIDD) { await MusicBot.SendVoiceData(buffer, 20, vnc); } else { goto label_31; } } else { goto label_18; } }while (MusicBot.IntPlayout > MusicBot.TotalSendBytes); Utils.Debug((object)"MusicBot, Finished playing?"); label_18: buffer = (byte[])null; } finally { if (foundationResampler != null) { foundationResampler.Dispose(); } } foundationResampler = (MediaFoundationResampler)null; } finally { if (waveStream != null) { waveStream.Dispose(); } } waveStream = (WaveStream)null; } catch (Exception ex) { Utils.Log(ex.StackTrace + "\n" + ex.Message, LogType.Error); } resampler = (MediaFoundationResampler)null; mediaStream = (WaveStream)null; OutFormat = (WaveFormat)null; goto label_33; } catch (Exception ex) { exc = ex; goto label_33; } label_31: num = 1; } catch (Exception ex) { obj = ex; } label_33: await vnc.SendSpeakingAsync(false); Exception obj1 = obj; if (obj1 != null) { Exception source = obj1 as Exception; if (source == null) { throw obj1; } ExceptionDispatchInfo.Capture(source).Throw(); } if (num == 1) { return; } obj = (Exception)null; if (exc == null) { return; } Utils.Log(string.Format("An exception occured during playback: `{0}: {1}`", (object)exc.GetType(), (object)exc.Message), LogType.Error); } }
public void SendAudioFile(string file) { DiscordVoiceClient vc = client.GetVoiceClient(); try { int ms = vc.VoiceConfig.FrameLengthMs; int channels = vc.VoiceConfig.Channels; int sampleRate = 48000; var outFormat = new WaveFormat(sampleRate, 16, channels); //int blockSize = 48 * 2 * channels * ms; int blockSize = 48 * 2 * channels * ms; byte[] buffer = new byte[blockSize]; vc.SetSpeaking(true); string fileFormat = file.Split(new char[] { '.' }).Last(); if (fileFormat == "mp3") { using (var mp3Reader = new Mp3FileReader(file)) using (var resampler = new MediaFoundationResampler(mp3Reader, outFormat)) { resampler.ResamplerQuality = 60; int byteCount; while ((byteCount = resampler.Read(buffer, 0, buffer.Length)) > 0) { if (byteCount < blockSize) { for (int i = byteCount; i < blockSize; i++) { buffer[i] = 0; } } SendBytes(buffer); } resampler.Dispose(); mp3Reader.Close(); } } else if (fileFormat == "wav") { using (var wavReader = new WaveFileReader(file)) using (var resampler = new MediaFoundationResampler(wavReader, outFormat)) { resampler.ResamplerQuality = 60; int byteCount; while ((byteCount = resampler.Read(buffer, 0, buffer.Length)) > 0) { if (byteCount < blockSize) { for (int i = byteCount; i < blockSize; i++) { buffer[i] = 0; } } SendBytes(buffer); } resampler.Dispose(); wavReader.Close(); } } else { throw new NotSupportedException($"File format \"{fileFormat}\" is not supported."); } } catch (Exception ex) { client.GetTextClientLogger.Log(ex.Message, MessageLevel.Critical); } }
public void Dispose() => resampler?.Dispose();