Beispiel #1
0
        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);
                    }
                }
        }
Beispiel #2
0
        private static async void SendMP3AudioFile(string filePath)
        {
            Channel channel = _audioClient.Channel;

            filePath = ConvertToMp3(filePath);

            int channelCount = _client.GetService <AudioService>().Config.Channels;

            NAudio.Wave.WaveFormat OutFormat = new NAudio.Wave.WaveFormat(48000, 16, channelCount);
            using (NAudio.Wave.Mp3FileReader MP3Reader = new NAudio.Wave.Mp3FileReader(filePath))
            {
                using (NAudio.Wave.MediaFoundationResampler resampler = new NAudio.Wave.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;
                            }
                        }

                        if (_audioClient.State == ConnectionState.Disconnecting || _audioClient.State == ConnectionState.Disconnected)
                        {
                            System.Threading.Thread.Sleep(1000);
                        }

                        try
                        {
                            _audioClient.Send(buffer, 0, blockSize);
                        }
#pragma warning disable CS0168 // Variable is declared but never used, supressed error because it must be declared to be caught
                        catch (OperationCanceledException e)
#pragma warning restore CS0168
                        {
                            //if (!(_audioClient.State == ConnectionState.Disconnecting || _audioClient.State == ConnectionState.Disconnected))
                            //{
                            _audioClient = await JoinAudioChannel(channel);

                            System.Threading.Thread.Sleep(1000);
                            _audioClient.Send(buffer, 0, blockSize);
                            //}
                        }
                    }
                    //await _audioClient.Disconnect();
                }
            }
            _nextSong = true;
        }
Beispiel #3
0
        /// <summary>
        /// Send audio to the current _vClient channel
        /// </summary>
        /// <param name="path">Path of the .wav file to send</param>
        private void send(string path, Command current, IAudioClient _vClient)
        {
            int blockSize = 3840; // The size of bytes to read per frame; 1920 for mono

            try
            {
                using (FileStream f = File.Open(path, FileMode.Open))
                {
                    byte[] buffer = new byte[blockSize];
                    while (f.Read(buffer, 0, buffer.Length) > 0)
                    {
                        try { _vClient.Send(buffer, 0, buffer.Length); }
                        catch (Discord.Net.TimeoutException e)
                        {
                            log.Error("Error sending audio data: " + e.Message);
                        }
                    }

                    _vClient.Wait();
                    log.Info("Sent audio: " + path);
                }
            }
            catch (FileNotFoundException e) { log.Error(string.Format("Could not find file; ensure {0} is correct path", path)); }
            catch (Exception e) { log.Error(e); }
        }
Beispiel #4
0
        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);
        }
        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);
        }
Beispiel #6
0
        private void SendAudioData(IAudioClient audioClient, PlayRequest request)
        {
            try
            {
                var file = request.File;
                var cancellationToken = request.TokenSource.Token;

                using (var reader = File.OpenRead(file))
                {
                    byte[] buffer = new byte[BLOCK_SIZE];
                    int    byteCount;

                    while ((byteCount = reader.Read(buffer, 0, BLOCK_SIZE)) > 0)
                    {
                        if (cancellationToken.IsCancellationRequested)
                        {
                            audioClient.Clear();
                            return;
                        }

                        audioClient.Send(buffer, 0, byteCount);
                    }
                }

                audioClient.Wait();
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message, ex);
            }
        }
 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;
             }
     }
 }
Beispiel #8
0
        public static async Task PlayMusic(IAudioClient voiceClient, string file)
        {
            var ffmpegProcess = new ProcessStartInfo();

            ffmpegProcess.FileName = @"C:\FFMPEG\bin\ffmpeg.exe";
            ffmpegProcess.Arguments = $"-i {file} -f s16le -ar 48000 -ac 2 pipe:1 -loglevel quiet";
            ffmpegProcess.UseShellExecute = false;
            ffmpegProcess.RedirectStandardOutput = true;

            var p = Process.Start(ffmpegProcess);

            await Task.Delay(1000); //give it 2 seconds to get some dataz
            int blockSize = 3840; // 1920 for mono
            byte[] buffer = new byte[blockSize];
            int read;
            while (!MilliaBot.IsSkipSong)
            {
                read = p.StandardOutput.BaseStream.Read(buffer, 0, blockSize);
                if (read == 0 || MilliaBot.IsSkipSong)
                {
                    MilliaBot.IsSkipSong = false;
                    await Task.Delay(1000);
                    break; //nothing to read
                }
                voiceClient.Send(buffer, 0, read);
            }
            voiceClient.Wait();
        }
Beispiel #9
0
        } //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
        /// <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 PlayFile(IAudioClient ac, string path)
        {
            var process = Process.Start(new ProcessStartInfo
            { // FFmpeg requires us to spawn a process and hook into its stdout, so we will create a Process
                FileName  = "ffmpeg",
                Arguments = $"-i {path} " +
                            "-f s16le -ar 48000 -ac 2 pipe:1",
                UseShellExecute        = false,
                RedirectStandardOutput = true
            });

            Thread.Sleep(200); // Sleep for a few seconds to FFmpeg can start processing data.

            int blockSize = 3840;

            byte[] buffer = new byte[blockSize];
            int    byteCount;

            while (true)
            {
                byteCount = process.StandardOutput.BaseStream
                            .Read(buffer, 0, blockSize);

                if (byteCount == 0) // FFmpeg did not output anything
                {
                    break;          // Break out of the while(true) loop, since there was nothing to read.
                }
                ac.Send(buffer, 0, byteCount);
            }
            ac.Wait(); // Wait for the Voice Client to finish sending data
        }
Beispiel #12
0
        private async Task SendSound(string song)
        {
            if (!_playing)
            {
                _vclient = await _client.GetService <AudioService>().Join(channel);

                _playing = true;
            }
            _skipThis = false;
            await Task.Run(() =>
            {
                int channelCount     = _client.GetService <AudioService>().Config.Channels;
                WaveFormat outFormat = new WaveFormat(48000, 16, channelCount);
                AudioFileReader r    = new AudioFileReader(song);
                using (MediaFoundationResampler resampler = new MediaFoundationResampler(r, 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)
                    {
                        r.Volume = volume;
                        if (byteCount < blockSize)
                        {
                            // Incomplete Frame
                            for (int i = byteCount; i < blockSize; i++)
                            {
                                buffer[i] = 0;
                                if (_skipThis)
                                {
                                    _vclient.Clear();
                                    break;
                                }
                            }
                        }
                        _vclient.Send(buffer, 0, blockSize);
                        _vclient.Wait();
                    }

                    GetNextSong();
                }
            });
        }
Beispiel #13
0
        internal async Task Play(IAudioClient voiceClient, CancellationToken cancelToken)
        {
            var       bufferTask     = BufferSong(cancelToken).ConfigureAwait(false);
            var       bufferAttempts = 0;
            const int waitPerAttempt = 500;
            var       toAttemptTimes = SongInfo.ProviderType != MusicType.Normal ? 5 : 9;

            while (!prebufferingComplete && bufferAttempts++ < toAttemptTimes)
            {
                await Task.Delay(waitPerAttempt, cancelToken).ConfigureAwait(false);
            }
            cancelToken.ThrowIfCancellationRequested();
            Console.WriteLine($"Prebuffering done? in {waitPerAttempt * bufferAttempts}");
            const int blockSize = 3840;
            var       attempt   = 0;

            while (!cancelToken.IsCancellationRequested)
            {
                //Console.WriteLine($"Read: {songBuffer.ReadPosition}\nWrite: {songBuffer.WritePosition}\nContentLength:{songBuffer.ContentLength}\n---------");
                byte[] buffer = new byte[blockSize];
                var    read   = songBuffer.Read(buffer, blockSize);
                unchecked
                {
                    bytesSent += (ulong)read;
                }
                if (read == 0)
                {
                    if (attempt++ == 20)
                    {
                        voiceClient.Wait();
                        Console.WriteLine($"Song finished. [{songBuffer.ContentLength}]");
                        break;
                    }
                    else
                    {
                        await Task.Delay(100, cancelToken).ConfigureAwait(false);
                    }
                }
                else
                {
                    attempt = 0;
                }

                while (this.MusicPlayer.Paused)
                {
                    await Task.Delay(200, cancelToken).ConfigureAwait(false);
                }
                buffer = AdjustVolume(buffer, MusicPlayer.Volume);
                voiceClient.Send(buffer, 0, read);
            }
            Console.WriteLine("Awiting buffer task");
            await bufferTask;

            Console.WriteLine("Buffer task done.");
            voiceClient.Clear();
            cancelToken.ThrowIfCancellationRequested();
        }
Beispiel #14
0
        /// <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();
        }
Beispiel #15
0
        internal async Task Play(IAudioClient voiceClient, CancellationToken cancelToken)
        {
            var t = BufferSong(cancelToken).ConfigureAwait(false);
            int bufferAttempts = 0;
            int waitPerAttempt = 500;
            int toAttemptTimes = SongInfo.ProviderType != MusicType.Normal ? 5 : 9;

            while (!prebufferingComplete && bufferAttempts++ < toAttemptTimes)
            {
                await Task.Delay(waitPerAttempt);
            }
            Console.WriteLine($"Prebuffering done? in {waitPerAttempt * bufferAttempts}");
            int blockSize = 3840;

            byte[] buffer  = new byte[blockSize];
            int    attempt = 0;

            while (!cancelToken.IsCancellationRequested)
            {
                //Console.WriteLine($"Read: {songBuffer.ReadPosition}\nWrite: {songBuffer.WritePosition}\nContentLength:{songBuffer.ContentLength}\n---------");
                int read = songBuffer.Read(buffer, blockSize);
                if (read == 0)
                {
                    if (attempt++ == 10)
                    {
                        voiceClient.Wait();
                        Console.WriteLine("Playing done.");
                        return;
                    }
                    else
                    {
                        await Task.Delay(50);
                    }
                }
                else
                {
                    attempt = 0;
                }

                while (this.MusicPlayer.Paused)
                {
                    await Task.Delay(200);
                }
                buffer = adjustVolume(buffer, MusicPlayer.Volume);
                voiceClient.Send(buffer, 0, read);
            }
            //try {
            //    voiceClient.Clear();
            //    Console.WriteLine("CLEARED");
            //}
            //catch {
            //    Console.WriteLine("CLEAR FAILED!!!");
            //}
        }
Beispiel #16
0
        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();
        }
Beispiel #18
0
        public async Task SendMusic(IAudioClient _aClient, CancellationToken cancelToken)
        {
            AudioInfo aI = audioInfos.Where(x => x.id.Equals(_aClient.Server.Id)).FirstOrDefault();

            var bufferTask = ReadFromStream(_aClient.Server.Id, cancelToken);
            await Task.Delay(2000, cancelToken);

            const int blockSize = 3840;
            var       buffer    = new byte[blockSize];
            int       lag       = 0;
            int       lagged    = 0;

            while (true)
            {
                var read = aI.ringBuffer.Read(buffer, blockSize);
                if (read == 0)
                {
                    lag++; lagged++;
                }
                else
                {
                    if (lag >= 0)
                    {
                        lag--; lagged = 0;
                    }
                }
                if (lagged > 35000)
                {
                    Console.WriteLine("Terminating sound, too much lag.");
                    break;
                }
                if (lag > 10000)
                {
                    lag = 0;
                    await Task.Delay(10000);
                }
                if (aI.skip)
                {
                    continue;
                }
                if (aI.stopped)
                {
                    continue;
                }
                while (aI.softpause)
                {
                    await Task.Delay(10);
                }
                buffer = AdjustVolume(buffer, (float)aI.volume / 100);
                _aClient.Send(buffer, 0, read);
            }
            _client.Log.Debug("Finished playing song.", null);
            aI.playing = false;
        }
Beispiel #19
0
        // Streaming service for youtube audio stream
        public async Task YoutubeStream(string pathOrUrl, CommandEventArgs e)
        {
            Process process = Process.Start(new ProcessStartInfo
            {                                                  // FFmpeg requires us to spawn a process and hook into its stdout, so we will create a Process
                FileName  = "ffmpeg",
                Arguments = $"-i {pathOrUrl} " +               // Here we provide a list of arguments to feed into FFmpeg. -i means the location of the file/URL it will read from
                            "-f s16le -ar 48000 -ac 2 pipe:1", // Next, we tell it to output 16-bit 48000Hz PCM, over 2 channels, to stdout.
                UseShellExecute        = false,
                RedirectStandardOutput = true                  // Capture the stdout of the process
            });

            Thread.Sleep(2000);     // Sleep for a few seconds to FFmpeg can start processing data.

            int blockSize = 3840;   // The size of bytes to read per frame; 1920 for mono

            byte[] buffer = new byte[blockSize];
            int    byteCount;

            while (true)                                      // Loop forever, so data will always be read
            {
                byteCount = process.StandardOutput.BaseStream // Access the underlying MemoryStream from the stdout of FFmpeg
                            .Read(buffer, 0, blockSize);      // Read stdout into the buffer

                int breaklimit = 0;
                while (byteCount == 0 /*&& breaklimit != 5*/)     // counter for failed attempts and sleeps so ffmpeg can read more audio
                {
                    Thread.Sleep(2500);
                    breaklimit++;
                }


                _audio.Send(buffer, 0, byteCount); // Send our data to Discord
                if (breaklimit == 6)               // when the breaklimit reaches 6 failed attempts its fair to say that ffmpeg has either crashed or is finished with the song
                {
                    break;                         // breaks the audio stream
                }
            }
            _audio.Wait();     // Wait for the Voice Client to finish sending data, as ffMPEG may have already finished buffering out a song, and it is unsafe to return now.

            await NextSong(e); // starts the stream for the next song
        }
Beispiel #20
0
        private void PlayYouTube(IAudioClient audioClient, string youtubeURL)
        {
            IEnumerable <VideoInfo> downloadUrls = DownloadUrlResolver.GetDownloadUrls(youtubeURL);
            VideoInfo targetVideoInfo            = downloadUrls.First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 720);

            if (targetVideoInfo.RequiresDecryption)
            {
                DownloadUrlResolver.DecryptDownloadUrl(targetVideoInfo);
            }
            Console.WriteLine("Found download url {0}", targetVideoInfo.DownloadUrl);

            Process process = Process.Start(new ProcessStartInfo
            {
                FileName               = "ffmpeg",
                Arguments              = $"-i {targetVideoInfo.DownloadUrl} -f s16le -ar 48000 -ac 2 pipe:1",
                UseShellExecute        = false,
                RedirectStandardOutput = true
            });

            Console.WriteLine("Started ffmpeg");
            Thread.Sleep(5000);

            int blockSize = 3840;

            byte[] buffer = new byte[blockSize];
            int    byteCount;


            while (!shouldStop)
            {
                byteCount = process.StandardOutput.BaseStream.Read(buffer, 0, blockSize);

                if (byteCount == 0)
                {
                    break;
                }

                audioClient.Send(buffer, 0, byteCount);
            }
            audioClient.Wait();

            if (shouldStop)
            {
                process.Kill();
                shouldStop = false;
                audioClient.Disconnect();
            }
        }
Beispiel #21
0
        void OnAudioCaptured(object sender, WaveInEventArgs e)
        {
            short[] audioData = new short[e.BytesRecorded];

            audioData[0] = BitConverter.ToInt16(e.Buffer, 0);
            for (int i = 2; i < e.BytesRecorded - 1; i += 2)
            {
                audioData[i / 2] = BitConverter.ToInt16(e.Buffer, i);
            }

            byte[] encoded = new byte[1000];

            var len = encoder.Encode(audioData, 0, 960, encoded, 0, encoded.Length);

            //Array.Copy(encoded, encoded, len);
            audioSender.Send(encoded);
        }
Beispiel #22
0
        public static void SendAudio(string filePath, IAudioClient _vClient)
        {
            // Simple try and catch.
            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 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 = 30;                                       // 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 & isPlaying) // 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
            {
                System.Console.WriteLine("Something went wrong. :(");
            }
        }
Beispiel #23
0
        public void SendAudio(string uri, Func <bool> cancel = null)
        {
            var musicReader = Reader(uri);

            if (musicReader == null)
            {
                return;
            }
            var channels  = UFWBot.Audio.Config.Channels;
            var outFormat = new WaveFormat(48000, 16, channels);

            player  = true;
            skipper = false;
            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)
                    {
                        player = false;
                        break; // Break on failed read.
                    }
                    _vClient.Send(buffer, 0, blockSize);
                    if (end)
                    {
                        player = false;
                        break;
                    }
                    if (skipper)
                    {
                        player = false;
                        break;
                    }
                }
            }
            musicReader.Dispose();
        }
Beispiel #24
0
        private void PlayRequest(ArrayList musicQ, IAudioClient audio)  //FOR PLAYING OUR OWN LOCAL MP3 FILES
        {
            while (musicQ.Count != 0)
            {
                string filePath = (string)musicQ[0];
                if (addMp3 == true)
                {
                    filePath = filePath.Insert(0, "mu/");
                    filePath = filePath.Insert(filePath.Length, ".mp3");
                }
                System.Console.Write(filePath);
                string songName = filePath.Remove(0, 3);
                songName = songName.Remove(songName.Length - 4, 4);
                discord.SetGame(songName);
                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 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) && skipB != true) // 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;
                                }
                            }

                            audio.Send(buffer, 0, blockSize); // Send the buffer to Discord
                        }
                        skipB = false;
                    }
                musicQ.RemoveAt(0);//song over so remove from queue
            }
        }
Beispiel #25
0
        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);
            }
        }
Beispiel #26
0
        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();
        }
Beispiel #27
0
        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.
        }
Beispiel #28
0
        public void PlayMusic(string sample, IAudioClient voiceClient)
        {
            using (WaveFileReader pcm = new WaveFileReader(sample))
            {
                int blocksize = pcm.WaveFormat.AverageBytesPerSecond / 5;
                byte[] buffer = new byte[blocksize];
                int offset = 0;

                    try
                    {
                        while (offset < pcm.Length / blocksize && !skip)
                        {
                            if (currentPlaying != sample)
                            {

                            }

                            offset++;
                            pcm.Read(buffer, 0, blocksize);

                            voiceClient.Send(buffer, 0, blocksize);
                            //voiceClient.Wait();
                        }
                    }
                    catch (Exception e)
                    {
                        Console.Write(e.ToString());
                    }
            }
            return;
        }
Beispiel #29
0
        public void PlaySoundEffect(User user, Channel ch, string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                return;
            }

            // Ensure voice channel is connected

            ConnectToVoice();

            // Play the sound effect

            Task.Run(() =>
            {
                try
                {
                    sending.WaitOne();

                    var effect = SoundEffectRepository.FindByName(name);

                    if (audio != null && effect != null)
                    {
                        if (effect.Duration.TotalMilliseconds == 0)
                        {
                            return;
                        }

                        SoundboardLoggingService.Instance.Info(
                            string.Format("[{0}] playing <{1}>", user.Name, name));

                        // Change "playing" to the sound effect name

                        SetStatusMessage(name);

                        // Records play statistics

                        Statistics.Play(user, effect);

                        // Notify users soundbot will begin playing

                        SendMessage(ch, string.Format(Properties.Resources.MessagePlayingSound, name));

                        // Resample and stream sound effect over the configured voice channel

                        var format = new WaveFormat(48000, 16, 2);
                        var length = Convert.ToInt32(format.AverageBytesPerSecond / 60.0 * 1000.0);
                        var buffer = new byte[length];

                        using (var reader = new WaveFileReader(effect.Path))
                            using (var resampler = new WaveFormatConversionStream(format, reader))
                            {
                                int count = 0;
                                while ((count = resampler.Read(buffer, 0, length)) > 0)
                                {
                                    audio.Send(buffer, 0, count);
                                }
                            }

                        audio.Wait();

                        SetStatusMessage(Configuration.Status);
                    }
                }
                catch (Exception ex)
                {
                    SoundboardLoggingService.Instance.Error(
                        string.Format(Properties.Resources.MessagePlayingFailed, name), ex);
                }
                finally
                {
                    sending.Set();
                }
            });
        }
Beispiel #30
0
        internal async Task Play(IAudioClient voiceClient, CancellationToken cancelToken)
        {
            var filename = Path.Combine(MusicModule.MusicDataPath, DateTime.Now.UnixTimestamp().ToString());

            SongBuffer sb = new SongBuffer(filename, SongInfo, skipTo);
            var bufferTask = sb.BufferSong(cancelToken).ConfigureAwait(false);

            var inStream = new FileStream(sb.GetNextFile(), FileMode.OpenOrCreate, FileAccess.Read, FileShare.Write); ;

            bytesSent = 0;

            try
            {
                var attempt = 0;             

                var prebufferingTask = CheckPrebufferingAsync(inStream, sb, cancelToken);
                var sw = new Stopwatch();
                sw.Start();
                var t = await Task.WhenAny(prebufferingTask, Task.Delay(5000, cancelToken));
                if (t != prebufferingTask)
                {
                    Console.WriteLine("Prebuffering timed out or canceled. Cannot get any data from the stream.");
                    return;
                }
                else if(prebufferingTask.IsCanceled)
                {
                    Console.WriteLine("Prebuffering timed out. Cannot get any data from the stream.");
                    return;
                }
                sw.Stop();
                Console.WriteLine("Prebuffering successfully completed in "+ sw.Elapsed);

                const int blockSize = 3840;
                byte[] buffer = new byte[blockSize];
                while (!cancelToken.IsCancellationRequested)
                {
                    //Console.WriteLine($"Read: {songBuffer.ReadPosition}\nWrite: {songBuffer.WritePosition}\nContentLength:{songBuffer.ContentLength}\n---------");
                    var read = inStream.Read(buffer, 0, buffer.Length);
                    //await inStream.CopyToAsync(voiceClient.OutputStream);
                    unchecked
                    {
                        bytesSent += (ulong)read;
                    }
                    if (read < blockSize)
                    {
                        if (sb.IsNextFileReady())
                        {
                            inStream.Dispose();
                            inStream = new FileStream(sb.GetNextFile(), FileMode.Open, FileAccess.Read, FileShare.Write);
                            read += inStream.Read(buffer, read, buffer.Length - read);
                            attempt = 0;
                        }
                        if (read == 0)
                        {
                            if (sb.BufferingCompleted)
                                break;
                            if (attempt++ == 20)
                            {
                                voiceClient.Wait();
                                MusicPlayer.SongCancelSource.Cancel();
                                break;
                            }
                            else
                                await Task.Delay(100, cancelToken).ConfigureAwait(false);                         
                        }
                        else
                            attempt = 0;
                    }
                    else
                        attempt = 0;

                    while (this.MusicPlayer.Paused)
                        await Task.Delay(200, cancelToken).ConfigureAwait(false);

                    buffer = AdjustVolume(buffer, MusicPlayer.Volume);
                    voiceClient.Send(buffer, 0, read);
                }
            }
            finally
            {
                await bufferTask;
                await Task.Run(() => voiceClient.Clear());
                if(inStream != null)
                    inStream.Dispose();
                Console.WriteLine("l");
                sb.CleanFiles();
            }
        }
Beispiel #31
0
        internal async Task Play(IAudioClient voiceClient, CancellationToken cancelToken)
        {
            var filename = Path.Combine(MusicModule.MusicDataPath, DateTime.Now.UnixTimestamp().ToString());

            SongBuffer sb         = new SongBuffer(filename, SongInfo, skipTo);
            var        bufferTask = sb.BufferSong(cancelToken).ConfigureAwait(false);

            var inStream = new FileStream(sb.GetNextFile(), FileMode.OpenOrCreate, FileAccess.Read, FileShare.Write);;

            bytesSent = 0;

            try
            {
                var attempt = 0;

                var prebufferingTask = CheckPrebufferingAsync(inStream, sb, cancelToken);
                var sw = new Stopwatch();
                sw.Start();
                var t = await Task.WhenAny(prebufferingTask, Task.Delay(5000, cancelToken));

                if (t != prebufferingTask)
                {
                    Console.WriteLine("Prebuffering timed out or canceled. Cannot get any data from the stream.");
                    return;
                }
                else if (prebufferingTask.IsCanceled)
                {
                    Console.WriteLine("Prebuffering timed out. Cannot get any data from the stream.");
                    return;
                }
                sw.Stop();
                Console.WriteLine("Prebuffering successfully completed in " + sw.Elapsed);

                const int blockSize = 3840;
                byte[]    buffer    = new byte[blockSize];
                while (!cancelToken.IsCancellationRequested)
                {
                    //Console.WriteLine($"Read: {songBuffer.ReadPosition}\nWrite: {songBuffer.WritePosition}\nContentLength:{songBuffer.ContentLength}\n---------");
                    var read = inStream.Read(buffer, 0, buffer.Length);
                    //await inStream.CopyToAsync(voiceClient.OutputStream);
                    unchecked
                    {
                        bytesSent += (ulong)read;
                    }
                    if (read < blockSize)
                    {
                        if (sb.IsNextFileReady())
                        {
                            inStream.Dispose();
                            inStream = new FileStream(sb.GetNextFile(), FileMode.Open, FileAccess.Read, FileShare.Write);
                            read    += inStream.Read(buffer, read, buffer.Length - read);
                            attempt  = 0;
                        }
                        if (read == 0)
                        {
                            if (sb.BufferingCompleted)
                            {
                                break;
                            }
                            if (attempt++ == 20)
                            {
                                voiceClient.Wait();
                                MusicPlayer.SongCancelSource.Cancel();
                                break;
                            }
                            else
                            {
                                await Task.Delay(100, cancelToken).ConfigureAwait(false);
                            }
                        }
                        else
                        {
                            attempt = 0;
                        }
                    }
                    else
                    {
                        attempt = 0;
                    }

                    while (this.MusicPlayer.Paused)
                    {
                        await Task.Delay(200, cancelToken).ConfigureAwait(false);
                    }

                    buffer = AdjustVolume(buffer, MusicPlayer.Volume);
                    voiceClient.Send(buffer, 0, read);
                }
            }
            finally
            {
                await bufferTask;
                await Task.Run(() => voiceClient.Clear());

                if (inStream != null)
                {
                    inStream.Dispose();
                }
                Console.WriteLine("l");
                sb.CleanFiles();
            }
        }
Beispiel #32
0
        internal async Task Play(IAudioClient voiceClient, CancellationToken cancelToken)
        {
            var bufferTask = BufferSong(cancelToken).ConfigureAwait(false);
            var bufferAttempts = 0;
            const int waitPerAttempt = 500;
            var toAttemptTimes = SongInfo.ProviderType != MusicType.Normal ? 5 : 9;
            while (!prebufferingComplete && bufferAttempts++ < toAttemptTimes)
            {
                await Task.Delay(waitPerAttempt, cancelToken);
            }
            cancelToken.ThrowIfCancellationRequested();
            Console.WriteLine($"Prebuffering done? in {waitPerAttempt * bufferAttempts}");
            const int blockSize = 3840;
            var attempt = 0;
            while (!cancelToken.IsCancellationRequested)
            {
                //Console.WriteLine($"Read: {songBuffer.ReadPosition}\nWrite: {songBuffer.WritePosition}\nContentLength:{songBuffer.ContentLength}\n---------");
                byte[] buffer = new byte[blockSize];
                var read = songBuffer.Read(buffer, blockSize);
                unchecked
                {
                    bytesSent += (ulong)read;
                }
                if (read == 0)
                    if (attempt++ == 20)
                    {
                        voiceClient.Wait();
                        Console.WriteLine($"Song finished. [{songBuffer.ContentLength}]");
                        break;
                    }
                    else
                        await Task.Delay(100, cancelToken);
                else
                    attempt = 0;

                while (this.MusicPlayer.Paused)
                    await Task.Delay(200, cancelToken);
                buffer = AdjustVolume(buffer, MusicPlayer.Volume);
                voiceClient.Send(buffer, 0, read);
            }
            Console.WriteLine("Awiting buffer task");
            await bufferTask;
            Console.WriteLine("Buffer task done.");
            voiceClient.Clear();
            cancelToken.ThrowIfCancellationRequested();
        }
Beispiel #33
0
        //m r,radio - init
        //m n,next - next in que
        //m p,pause - pauses, call again to unpause
        //m yq [key_words] - queue from yt by keywords
        //m s,stop - stop
        //m sh - shuffle songs
        //m pl - current playlist

        public override void Install(ModuleManager manager)
        {
            var client = NadekoBot.client;

            manager.CreateCommands("!m", cgb => {
                //queue all more complex commands
                commands.ForEach(cmd => cmd.Init(cgb));

                cgb.CreateCommand("n")
                .Alias("next")
                .Description("Goes to the next song in the queue.")
                .Do(e => {
                    if (Voice != null && Exit == false)
                    {
                        NextSong = true;
                    }
                });

                cgb.CreateCommand("s")
                .Alias("stop")
                .Description("Completely stops the music and unbinds the bot from the channel.")
                .Do(e => {
                    if (Voice != null && Exit == false)
                    {
                        Exit      = true;
                        SongQueue = new List <YouTubeVideo>();
                    }
                });

                cgb.CreateCommand("p")
                .Alias("pause")
                .Description("Pauses the song")
                .Do(async e => {
                    if (Voice != null && Exit == false && CurrentSong != null)
                    {
                        Pause = !Pause;
                        if (Pause)
                        {
                            await e.Send("Pausing. Run the command again to resume.");
                        }
                        else
                        {
                            await e.Send("Resuming...");
                        }
                    }
                });

                cgb.CreateCommand("q")
                .Alias("yq")
                .Description("Queue a song using a multi/single word name.\n**Usage**: `!m q Dream Of Venice`")
                .Parameter("Query", ParameterType.Unparsed)
                .Do(async e => {
                    var youtube = YouTube.Default;
                    var video   = youtube.GetAllVideos(Searches.FindYoutubeUrlByKeywords(e.Args[0]))
                                  .Where(v => v.AdaptiveKind == AdaptiveKind.Audio)
                                  .OrderByDescending(v => v.AudioBitrate).FirstOrDefault();

                    if (video?.Uri != "" && video.Uri != null)
                    {
                        SongQueue.Add(video);
                        if (SongQueue.Count > 1)
                        {
                            await e.Send("**Queued** " + video.FullName);
                        }
                    }
                });

                cgb.CreateCommand("lq")
                .Alias("ls").Alias("lp")
                .Description("Lists up to 10 currently queued songs.")
                .Do(async e => {
                    await e.Send(SongQueue.Count + " videos currently queued.");
                    await e.Send(string.Join("\n", SongQueue.Select(v => v.FullName).Take(10)));
                });

                cgb.CreateCommand("sh")
                .Description("Shuffles the current playlist.")
                .Do(async e => {
                    if (SongQueue.Count < 2)
                    {
                        await e.Send("Not enough songs in order to perform the shuffle.");
                        return;
                    }

                    SongQueue.Shuffle();
                    await e.Send("Songs shuffled!");
                });

                cgb.CreateCommand("radio")
                .Alias("music")
                .Description("Binds to a voice and text channel in order to play music.")
                .Parameter("ChannelName", ParameterType.Unparsed)
                .Do(async e => {
                    if (Voice != null)
                    {
                        return;
                    }
                    VoiceChannel = e.Server.FindChannels(e.GetArg("ChannelName").Trim(), ChannelType.Voice).FirstOrDefault();
                    Voice        = await client.Audio().Join(VoiceChannel);
                    Exit         = false;
                    NextSong     = false;
                    Pause        = false;
                    try {
                        while (true)
                        {
                            if (Exit)
                            {
                                break;
                            }
                            if (SongQueue.Count == 0 || Pause)
                            {
                                Thread.Sleep(100); continue;
                            }
                            if (!LoadNextSong())
                            {
                                break;
                            }

                            await Task.Run(async() => {
                                if (Exit)
                                {
                                    Voice = null;
                                    Exit  = false;
                                    await e.Send("Exiting...");
                                    return;
                                }

                                var streamer = new AudioStreamer(Music.CurrentSong.Uri);
                                streamer.Start();
                                while (streamer.BytesSentToTranscoder < 100 * 0x1000 || streamer.NetworkDone)
                                {
                                    await Task.Delay(500);
                                }

                                int blockSize = 1920 * client.Audio().Config.Channels;
                                byte[] buffer = new byte[blockSize];

                                var msg     = await e.Send("Playing " + Music.CurrentSong.FullName + " [00:00]");
                                int counter = 0;
                                int byteCount;

                                while ((byteCount = streamer.PCMOutput.Read(buffer, 0, blockSize)) > 0)
                                {
                                    Voice.Send(buffer, byteCount);
                                    counter += blockSize;
                                    if (NextSong)
                                    {
                                        NextSong = false;
                                        break;
                                    }
                                    if (Exit)
                                    {
                                        Exit = false;
                                        return;
                                    }
                                    while (Pause)
                                    {
                                        Thread.Sleep(100);
                                    }
                                }
                            });
                        }
                        Voice.Wait();
                    } catch (Exception ex) { Console.WriteLine(ex.ToString()); }
                    await Voice.Disconnect();
                    Voice        = null;
                    VoiceChannel = null;
                });
            });
        }
Beispiel #34
0
        public BackgroundWorker SendAudio(string url, IAudioClient vClient)
        {
            #region Get video stream

            MemoryStream ms = new MemoryStream();

            bool   running = true;
            object msLock  = new object();


            //new Thread(delegate (object o)
            //{

            try
            {
                var response = WebRequest.Create(url).GetResponse();
                using (var stream = response.GetResponseStream())
                {
                    byte[] gettingBuffer = new byte[65536]; // 64KB chunks
                    int    read;
                    while ((read = stream.Read(gettingBuffer, 0, gettingBuffer.Length)) > 0)
                    {
                        lock (msLock)
                        {
                            // var pos = ms.Position;
                            //   ms.Position = ms.Length;
                            ms.Write(gettingBuffer, 0, read);
                            //   ms.Position = pos;
                        }
                    }
                }

                running = false;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            // }).Start();

            //  Pre-buffering some data to allow NAudio to start playing
            //   while (ms.Length < 65536 * 10 && running)
            //       Thread.Sleep(1000);



            ms.Position = 0;
            #endregion



            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.

            BackgroundWorker worker = new BackgroundWorker();
            worker.WorkerSupportsCancellation = true;

            using (var StreamFileReader = new StreamMediaFoundationReader(ms))                    // Create a new Disposable MP3FileReader, to read audio from the filePath parameter
                using (var resampler = new MediaFoundationResampler(StreamFileReader, 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 = 0;


                    worker.DoWork += new DoWorkEventHandler((object sender, DoWorkEventArgs e) =>
                    {
                        try
                        {
                            do
                            {
                                lock (msLock)
                                    byteCount = resampler.Read(buffer, 0, blockSize); // 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
                            }while (!worker.CancellationPending && (byteCount > 0 || running));

                            ms.Close();
                            ms.Dispose();
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    });

                    worker.RunWorkerAsync();
                }

            return(worker);
        }