public void PlayFile(string filePath) { var OutFormat = new WaveFormat(48000, 16, 1); // Create a new Output Format, using the spec that Discord will accept, and with the number of channels that our Client supports. AudioOutStream currentStream = AudioClient.CreatePCMStream(AudioApplication.Mixed); 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]; byte[] silence = new byte[blockSize]; int byteCount = resampler.Read(buffer, 0, blockSize); while (byteCount > 0) // Read audio into our buffer, and keep a loop open while data is present { if (RequestStop) { RequestStop = false; FinishedSong(); return; } if (byteCount < blockSize) { // Incomplete Frame for (int i = byteCount; i < blockSize; i++) { buffer[i] = 0; } } for (int i = 0; i < buffer.Length; i += 2) { short sample = (short)(buffer[i] | (buffer[i + 1] << 8)); short result = (short)(sample * Volume); buffer[i] = (byte)(result & 0xFF); buffer[i + 1] = (byte)(result >> 8); } try { currentStream.WriteAsync(Paused ? silence : buffer, 0, blockSize).GetAwaiter(); //Send buffer to Discord } catch (Exception e) { Console.WriteLine(e.Message); AudioClient = null; CurrentState = AudioState.Stopped; break; } if (!Paused) { byteCount = resampler.Read(buffer, 0, blockSize); } } FinishedSong(); } }
private Stream CompileMMX2(Stream basestream) { var mem = new MemoryStream(); using (var writer = new BinaryWriter(mem, Encoding.ASCII, true)) using (var wav = new WaveFileReader(basestream)) using (var res = new MediaFoundationResampler(wav, new WaveFormat( wav.WaveFormat.SampleRate < 24000 ? 24000 : 48000 , 1))) { var opus = OpusEncoder.Create(res.WaveFormat.SampleRate, 1, FragLabs.Audio.Codecs.Opus.Application.Voip); opus.Bitrate = PPeXCore.Settings.XggBitrate; int packetsize = (int)(res.WaveFormat.SampleRate * 2 * PPeXCore.Settings.XggFrameSize); writer.Write(Encoding.ASCII.GetBytes("XGG")); writer.Write(Version); writer.Write(packetsize); writer.Write(opus.Bitrate); long oldpos = mem.Position; ushort count = 0; writer.Write(count); byte[] uncompressed = new byte[10000 + (res.WaveFormat.AverageBytesPerSecond / wav.WaveFormat.AverageBytesPerSecond) * wav.Length]; byte[] buffer = new byte[packetsize]; int result = res.Read(buffer, 0, packetsize); int offset = 0; while (result > 0) { /* * count++; * int outlen = 0; * byte[] output = opus.Encode(buffer, result / 2, out outlen); * writer.Write((uint)outlen); * writer.Write(output, 0, outlen);*/ Array.Copy(buffer, 0, uncompressed, offset, result); offset += result; result = res.Read(buffer, 0, packetsize); } mem.Position = oldpos; writer.Write(count); } mem.Position = 0; _size = (uint)mem.Length; return(mem); }
public static async void StreamFileToVoiceChannel(string path, Channel vChannel) { IsPlaying = true; var vClient = await Bot.Client.GetService <AudioService>().Join(vChannel); var channelCount = Bot.Client.GetService <AudioService>().Config.Channels; var OutFormat = new WaveFormat(48000, 16, channelCount); using (var MP3Reader = new Mp3FileReader(path)) 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 /* && playing*/) { if (byteCount < blockSize) { for (int i = byteCount; i < blockSize; i++) { buffer[i] = 0; } } vClient.Send(buffer, 0, blockSize); } vClient.Wait(); } IsPlaying = false; await vClient.Disconnect(); }
public static void StartMusic(string filePath, DiscordClient discordBot, Channel voiceChannel, IAudioClient aService) { if (!isPlaying) { var channelCount = discordBot.GetService <AudioService>().Config.Channels; var OutFormat = new WaveFormat(48000, 16, channelCount); using (var AudioReader = new AudioFileReader(filePath)) using (var resampler = new MediaFoundationResampler(AudioReader, OutFormat)) { resampler.ResamplerQuality = 60; // Set the quality of the resampler to 60, the highest quality int blockSize = OutFormat.AverageBytesPerSecond / 50; byte[] buffer = new byte[blockSize]; int byteCount; isPlaying = true; while ((byteCount = resampler.Read(buffer, 0, blockSize)) > 0) { if (byteCount < blockSize) { for (int i = byteCount; i < blockSize; i++) { buffer[i] = 0; } } aService.Send(buffer, 0, blockSize); } isPlaying = false; } } }
internal void PlayUri(Discord.Audio.IAudioClient _client, string uri, Func <bool> cancel = null) { var musicReader = Reader(uri); if (musicReader == null) { Program.log.Warning("Stream", $"{uri} couldn't be read."); return; } var channels = Program.Audio.Config.Channels; var outFormat = new WaveFormat(48000, 16, channels); using (var resampler = new MediaFoundationResampler(musicReader, outFormat) { ResamplerQuality = 60 }) { int blockSize = outFormat.AverageBytesPerSecond; // 1 second byte[] buffer = new byte[blockSize]; while (cancel == null || !cancel()) { bool end = musicReader.Position + blockSize > musicReader.Length; // Stop at the end, work around the bug that has it Read twice. if (resampler.Read(buffer, 0, blockSize) <= 0) { break; // Break on failed read. } _client.Send(buffer, 0, blockSize); if (end) { break; } } } musicReader.Dispose(); }
public async Task <(string fileName, int rate)> CompressAudio(Stream fileStream, Action <int> onProgress = null) { var outFormat = new WaveFormat(16000, 1); var fileName = $"{Guid.NewGuid()}.wav"; using (var reader = new Mp3FileReader(fileStream)) using (var resampler = new MediaFoundationResampler(reader, outFormat) { ResamplerQuality = 60 }) using (var outStream = File.Create(fileName)) using (var writer = new WaveFileWriter(outStream, outFormat)) { var buffer = new byte[outFormat.AverageBytesPerSecond * 4]; var targetSize = outFormat.AverageBytesPerSecond * reader.TotalTime.TotalSeconds; var readed = 0; while (true) { int bytesRead = resampler.Read(buffer, 0, buffer.Length); readed += bytesRead; onProgress?.Invoke((int)(readed / targetSize * 100)); if (bytesRead == 0) { // end of source provider break; } // Write will throw exception if WAV file becomes too large await outStream.WriteAsync(buffer, 0, bytesRead); } } return(fileName, 16000); }
/// <summary> /// Reproduce an audio in a channel. /// </summary> /// <param name="channel">Target channel.</param> public byte[] Reproduce(IWaveProvider audio) { List <byte> bytes = new List <byte>(); // Create a Disposable Resampler, which will convert the read MP3 data to PCM, using our Output Format using (var resampler = new MediaFoundationResampler(audio, AudioHelpers.PcmFormat)) { resampler.ResamplerQuality = 60; int blockSize = AudioHelpers.PcmFormat.AverageBytesPerSecond / 50; byte[] buffer = new byte[blockSize]; int byteCount; // Read audio into our buffer, and keep a loop open while data is present while ((byteCount = resampler.Read(buffer, 0, blockSize)) > 0) { if (byteCount < blockSize) { // Incomplete Frame for (int i = byteCount; i < blockSize; i++) { buffer[i] = 0; } } bytes.AddRange(buffer); } } return(bytes.ToArray()); }
private void sendAudio(string filePath) { var channelCount = client.GetService <AudioService>().Config.Channels; var OutFormat = new WaveFormat(48000, 16, channelCount); using (var MP3Reader = new Mp3FileReader(filePath)) 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; } } audioClient.Send(buffer, 0, blockSize); } } }
private void sendAudioUsingDiscordHQ(Stream stream) { var channelCount = client.GetService <AudioService>().Config.Channels; var OutFormat = new WaveFormat(48000, 16, channelCount); stream.Position = 0; using (var AACReader = new MediaFoundationReader(stream)) using (var resampler = new MediaFoundationResampler(AACReader, OutFormat)) { resampler.ResamplerQuality = 60; int blockSize = OutFormat.AverageBytesPerSecond / 50; //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; } } audioClient.Send(buffer, 0, blockSize); } } }
public async Task Say([Remainder]string text = null) { await Stop(); var outFormat = new WaveFormat(48000, 16, 2); using (var ss = new SpeechSynthesizer()) using (var discord = _vClient.CreatePCMStream(AudioApplication.Music)) using (var tstream = new MemoryStream()) { ss.Volume = 100; ss.SelectVoiceByHints(VoiceGender.Female, VoiceAge.Adult, 0, new System.Globalization.CultureInfo("nl-NL")); ss.SetOutputToWaveStream(tstream); ss.Speak(text); tstream.Flush(); tstream.Seek(0, SeekOrigin.Begin); using (var wave = new WaveFileReader(tstream)) using (var resampler = new MediaFoundationResampler(wave, 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; } } discord.Write(buffer, 0, blockSize); } wave.Flush(); } tstream.Flush(); discord.Flush(); } }
public CachedSound(string audioFileName, int playerSampleRate = 44100) { using (var audioFileReader = new AudioFileReader(audioFileName)) { WaveFormat = audioFileReader.WaveFormat; if (WaveFormat.SampleRate != playerSampleRate) { using (var resampler = new MediaFoundationResampler(audioFileReader, playerSampleRate)) { var wholeFile = new List <byte>(); var readBuffer = new byte[resampler.WaveFormat.SampleRate * resampler.WaveFormat.Channels]; int samplesRead; while ((samplesRead = resampler.Read(readBuffer, 0, readBuffer.Length)) > 0) { wholeFile.AddRange(readBuffer.Take(samplesRead)); } AudioData = new float[wholeFile.Count / 4]; Buffer.BlockCopy(wholeFile.ToArray(), 0, AudioData, 0, wholeFile.Count); WaveFormat = new WaveFormat(playerSampleRate, audioFileReader.WaveFormat.Channels); } } else { 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(); } } }
/// <summary> /// Plays an mp3 file in the current voiceChannel /// </summary> /// <param name="filePath">Path for mp3 file</param> private void SendAudio(string filePath) { voiceClient.Wait(); var channelCount = 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(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; } } voiceClient.Send(buffer, 0, blockSize); // Send the buffer to Discord } } }
public void WriteAudioStream( Stream outputStream, string audioFile) { using (var audio = new AudioFileReader(audioFile)) using (var resampler = new MediaFoundationResampler(audio, DiscordOutputFormat)) { resampler.ResamplerQuality = 60; var blockSize = DiscordOutputFormat.AverageBytesPerSecond / 50; var buffer = new byte[blockSize]; var byteCount = 0; while ((byteCount = resampler.Read(buffer, 0, blockSize)) > 0) { if (byteCount < blockSize) { for (int i = byteCount; i < blockSize; i++) { buffer[i] = 0; } } outputStream.Write(buffer, 0, buffer.Length); } } }
/// <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; //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); } } }
//https://github.com/naudio/NAudio/issues/174 dan geliştirdiğim ve WaveFormatConvert yarattım. // Ses kartından gelen sesleri resample yani yeniden örneklemeye çalıştığımızdan Hz değerlerinin aynı olmasına dikkat edelim. /* * Ses kartından gelen değerler Örnek: * 48000 Hz(Sample Rate) 24 bit STEREO * -> Convert * 48000 Hz(Sample Rate) 16 bit STEREO olacak şekilde daha iyi ses alırız. */ public byte[] WaveFormatConvert(byte[] input, int length, WaveFormat inFormat, WaveFormat outFormat) { if (length == 0) { return(new byte[0]); } using (var memStream = new MemoryStream(input, 0, length)) { using (var inputStream = new RawSourceWaveStream(memStream, inFormat)) { using (var resampler = new MediaFoundationResampler(inputStream, outFormat)) { resampler.ResamplerQuality = sesKalitesi; // 1 low - 60 max high //CONVERTED READ STREAM byte[] buffer = new byte[length]; using (var stream = new MemoryStream()) { int read; while ((read = resampler.Read(buffer, 0, length)) > 0) { stream.Write(buffer, 0, read); } return(stream.ToArray()); } } } } }
} //plays music from a set folder until it is kicked. public void SendAudio(string filePath, IAudioClient _vClient) { var channelCount = discord.GetService <AudioService>().Config.Channels; var OutFormat = new WaveFormat(48000, 16, channelCount); using (var MP3Reader = new Mp3FileReader(filePath)) using (var resampler = new MediaFoundationResampler(MP3Reader, OutFormat)) { resampler.ResamplerQuality = 60; int blockSize = OutFormat.AverageBytesPerSecond / 50; // Establish the size of the AudioBuffer byte[] buffer = new byte[blockSize]; int byteCount; while ((byteCount = resampler.Read(buffer, 0, blockSize)) > 0) // Read audio into the 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); } } } //sends a mp3 to Discord
private async Task EncodeByNAudio( string wave, Func <byte[], int, Task> sendDelegate) { using (var audio = new AudioFileReader(wave)) using (var resampler = new MediaFoundationResampler(audio, DiscordOutputFormat)) { resampler.ResamplerQuality = 60; var blockSize = DiscordOutputFormat.AverageBytesPerSecond / 50; var buffer = new byte[blockSize]; var byteCount = 0; while ((byteCount = resampler.Read(buffer, 0, blockSize)) > 0) { if (byteCount < blockSize) { for (int i = byteCount; i < blockSize; i++) { buffer[i] = 0; } } await sendDelegate(buffer, blockSize); } } }
public byte[] RenderNewFormat(float masterVolume, WaveFormat newFormat) { if (Data != null && Data.Length > 0) { using (MemoryStream mem = new MemoryStream()) { MemoryStream dataStream = new MemoryStream(Render(masterVolume)); RawSourceWaveStream wavStream = new RawSourceWaveStream(dataStream, Format); byte[] buffer; int bytesRead; using (MediaFoundationResampler resampler = new MediaFoundationResampler(wavStream, newFormat)) { double c1 = (double)resampler.WaveFormat.SampleRate / wavStream.WaveFormat.SampleRate; double c2 = (double)resampler.WaveFormat.BitsPerSample / wavStream.WaveFormat.BitsPerSample; double c3 = (double)resampler.WaveFormat.Channels / wavStream.WaveFormat.Channels; buffer = new byte[(int)(wavStream.Length * (c1 * c2 * c3))]; resampler.Read(buffer, 0, buffer.Length); } return(buffer); } } return(Data); }
private void DataOutputExec() { var read_size = 0; while ((!play_complete_) && (read_size < sampling_buffer_.Length)) { read_size += resampler_.Read(sampling_buffer_, read_size, sampling_buffer_.Length - read_size); /* データバッファが一杯にならないときは最初から読み込む */ if (read_size < sampling_buffer_.Length) { if ((devp_.RepeatCount.Value == 0) || ((repeat_count_ + 1) < devp_.RepeatCount.Value)) { /* 繰り返し設定が有効かつ繰り返しが可能のとき */ reader_.Position = 0; repeat_count_++; } else { /* 再生終了 */ play_complete_ = true; } } } if (read_size > 0) { /* データ出力 */ NotifyRecvComplete( "", "", "", (read_size < sampling_buffer_.Length) ? (ClassUtil.CloneCopy(sampling_buffer_, 0, read_size)) : (sampling_buffer_)); } }
/// <summary> /// Initializes this resampler with the given input audio source and output format. /// Attaches to the given source's event to start resampling as soon as <see cref="IStreamAudioSource.DataAvailable"/> is raised. /// </summary> /// <param name="audioSource"></param> /// <param name="outputFormat"></param> public void Initialize(IStreamAudioSource audioSource, WaveStreamAudioFormat outputFormat) { this.WaveProviderAdapter = new NAudioStreamAudioSourceToWaveProviderAdapterSimple(audioSource); this.Resampler = new MediaFoundationResampler(this.WaveProviderAdapter, NAudioUtilities.ToNAudioWaveFormat(outputFormat)); //set this *after* we initialize the resampler. if it throws, we won't dispose the input audio source by accident this.WrappedAudioSource = audioSource; this.Format = outputFormat; //handle events from the wrapped source audioSource.DataAvailable += (s, e) => { //feed into our adapter WaveProviderAdapter.Write(e); //read from resampler and trigger our own output event int read; while ((read = Resampler.Read(Buffer, 0, Buffer.Length)) > 0) { DataAvailable?.Invoke(this, new StreamAudioSourceDataEvent() { Buffer = new ArraySegment <byte>(Buffer, 0, read), Format = Format }); } }; }
public static void playAudio(string filePath, IAudioClient voiceClient, DiscordClient discord) { System.Threading.Thread.Sleep(500); var channelCount = discord.GetService <AudioService>().Config.Channels; var OutFormat = new WaveFormat(48000, 16, channelCount); using (var MP3Reader = new Mp3FileReader(filePath)) 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; } } voiceClient.Send(buffer, 0, blockSize); } } System.Threading.Thread.Sleep(1000); }
public bool?SendAudio(Channel voiceChannel, IAudioClient _vClient, int quality = 20) { bool isFinished = false; var channelCount = _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. MemoryStream mp3file = new MemoryStream(File.ReadAllBytes(AppDomain.CurrentDomain.BaseDirectory + "topkek.mp3") /* Properties.Resources.topkek */); using (var MP3Reader = new Mp3FileReader(mp3file)) // 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 = quality; // Set the quality of the resampler to 20, a good 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); NonBlockingConsole.WriteLine($"omg i sent something ? noh ?");// Send the buffer to Discord } isFinished = true; } return(isFinished); }
private Task BufferClip(string clip) { return(Task.Factory.StartNew(() => { try { 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(clip)) // 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; if (m_outStream == null) { m_outStream = m_audioClient.CreatePCMStream(AudioApplication.Mixed, bufferMillis: 10); } int writes = 0; while ((byteCount = resampler.Read(buffer, 0, blockSize)) > 0) // Read audio into our buffer, and keep a loop open while data is present { if (m_clipCancellationSource.Token.IsCancellationRequested) { m_clipCancellationSource = new CancellationTokenSource(); return; } if (byteCount < blockSize) { // Incomplete Frame for (int i = byteCount; i < blockSize; i++) { buffer[i] = 0; } } lock (m_playbackMutex) { if (m_outStream != null) { m_outStream.Write(buffer, 0, blockSize); // Send the buffer to Discord } } writes++; } } } catch { //this is ok for the moment as currently it may assert if the channel changes m_outStream = null; } //} while (dequeued); }, m_clipCancellationSource.Token)); }
/// <summary> /// /// </summary> /// <param name="filepath"> /// Full filepath needed to track /// </param> /// <param name="voiceChannel"> /// Send the room that the bot is in /// </param> /// <param name="_client"> /// _client /// </param> /// <returns></returns> public async Task SendAudio(string filepath, Channel voiceChannel, DiscordClient _client) { //try to find a way to tell if she is already in 1. connect to a voice room and 2 in your voice room _nAudio = await _client.GetService <AudioService>().Join(voiceChannel); playingSong = true; try { var channelCount = _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 MediaFoundationReader(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; // Add in the "&& playingSong" so that it only plays while true. For our cheesy skip command. // AGAIN WARNING YOU NEED opus.dll libsodium.dll // If you do not have these, this will not work. try { while ((byteCount = resampler.Read(buffer, 0, blockSize)) > 0 && playingSong) // Read audio into our buffer, and keep a loop open while data is present { //adjust volume byte[] adjustedBuffer = ScaleVolumeSafeAllocateBuffers(buffer, volume); if (byteCount < blockSize) { // Incomplete Frame for (int i = byteCount; i < blockSize; i++) { buffer[i] = 0; } } _nAudio.Send(adjustedBuffer, 0, blockSize); // Send the buffer to Discord } } catch (Exception error) { await _client.GetService <AudioService>().Join(voiceChannel); Console.WriteLine(error.ToString()); } //await _nAudio.Disconnect(); } } catch (Exception error) { System.Console.WriteLine("Something went wrong. :("); } //await _nAudio.Disconnect(); }
public bool?SendAudio(Channel voiceChannel, IAudioClient _vClient, CancellationTokenSource cancel, int quality = 20) { bool isFinished = false; var channelCount = _client.GetService <AudioService>().Config.Channels; // Get the number of AudioChannels our AudioService has been configured to use. MemoryStream mp3file; 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. try { mp3file = new MemoryStream(File.ReadAllBytes(AppDomain.CurrentDomain.BaseDirectory + "topkek.mp3")); } catch (Exception ex) { NonBlockingConsole.WriteLine($"Ok so {AppDomain.CurrentDomain.BaseDirectory} and also {ex.Message} with {ex.StackTrace}"); Console.ReadKey(); throw; } using (var MP3Reader = new Mp3FileReader(mp3file)) // 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 = quality; // Set the quality of the resampler to 20, a good 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 && !cancel.IsCancellationRequested) // Read audio into our buffer, and keep a loop open while data is present { try { if (byteCount < blockSize) { // Incomplete Frame for (int i = byteCount; i < blockSize; i++) { buffer[i] = 0; } } if (!cancel.IsCancellationRequested) { _vClient.Send(buffer, 0, blockSize); // Send the buffer to Discord } } catch (OperationCanceledException) { _vClient.Channel.LeaveAudio(); } } } isFinished = true; return(isFinished); }
// Thank you Rand from the "Discord API" Discord for this peace of code ajusted by me to fit this project //(https://github.com/DjRand/) public static async Task SendAudio(string filepath, Channel voiceChannel) { // When we use the !play command, it'll start this method // The comment below is how you'd find the first voice channel on the server "Somewhere" //var voiceChannel = _client.FindServers("Somewhere").FirstOrDefault().VoiceChannels.FirstOrDefault(); // Since we already know the voice channel, we don't need that. // So... join the voice channel: _vClient = await bot.GetService <AudioService>().Join(voiceChannel); // Simple try and catch. try { 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; // Add in the "&& playingSong" so that it only plays while true. For our cheesy skip command. // AGAIN // WARNING // YOU NEED // vvvvvvvvvvvvvvv // opus.dll // libsodium.dll // ^^^^^^^^^^^^^^^ // If you do not have these, this will not work. 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 } await _vClient.Disconnect(); } } catch { System.Console.WriteLine("Something went wrong. :("); } await _vClient.Disconnect(); }
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)); } } }
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 }
public async void SendAudio(string filePath, MessageEventArgs e) { try { if (_Audio == true) { _client.UsingAudio(x => { x.Mode = AudioMode.Outgoing; }); } _Audio = false; _Playing = true; var voiceChannel = e.Message.Server.VoiceChannels.FirstOrDefault(); if (e.Message.User.VoiceChannel != null) { voiceChannel = e.Message.User.VoiceChannel; } var _vClient = await voiceChannel.JoinAudio(); var channelCount = 2; var OutFormat = new WaveFormat(48000, 16, channelCount); using (var MP3Reader = new Mp3FileReader("Audio/" + filePath)) 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 && _Playing == true) { if (byteCount < blockSize) { // Incomplete Frame for (int i = byteCount; i < blockSize; i++) { buffer[i] = 0; } } _vClient.Send(buffer, 0, blockSize); } } } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"{DateTime.Now} - Exception: {ex.Message}"); Console.ResetColor(); } }
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); }