Example #1
0
 public SodiumEncryptStream(AudioStream next, IAudioClient client, int bufferSize = 4000)
 {
     _next   = next;
     _client = (AudioClient)client;
     _nonce  = new byte[24];
     _buffer = new byte[bufferSize];
 }
Example #2
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;
        }
Example #3
0
        public static async Task JoinChannel(IAudioChannel channel)
        {
            client = await channel.ConnectAsync();

            Enabled        = true;
            CurrentChannel = channel;
        }
Example #4
0
        /*Voice channel tools*/
        private async Task NextSong()
        {
            if (VoiceInfo.PreviousVoiceChannelIndex == -1)
            {
                return;
            }

            //Load
            List <string> entries = LoadPlaylist();

            //Remove the previous played song from the queue
            if (entries.Count != 0)
            {
                entries.RemoveAt(0);
            }

            //Save
            SavePlaylist(entries);

            //Play if theres any songs left on queue
            if (entries.Count != 0)
            {
                List <SocketVoiceChannel> voiceChannels = Context.Guild.VoiceChannels.ToList <SocketVoiceChannel>();
                IAudioClient audioClient = await voiceChannels[VoiceInfo.PreviousVoiceChannelIndex].ConnectAsync();
                VoiceInfo.PreviousAudioClient = audioClient;
                await SendAsync(audioClient, entries[0]);
            }
        }
Example #5
0
        public async Task <bool> ConnectVoiceChannel(SocketVoiceChannel voiceChannel)
        {
            await DisconnectCurrentVoiceChannel();

            if (voiceChannel == null)
            {
                throw new ArgumentNullException("VoiceChannel is null");
            }

            CurrentVoiceChannel = voiceChannel;

            // ボイスチャンネルへの接続を開始
            // 音声の送信はConnectedイベント後
            // 受信はStreamCreatedイベント後に行われます
            using (var releaser = await _VoiceChannelLock.LockAsync())
            {
                await voiceChannel.ConnectAsync((client) =>
                {
                    _CurrentVoiceAudioClient = client;
                    client.Connected        += VoiceChannelConnected;
                    client.Disconnected     += VoiceChannelDisconnected;
                    client.LatencyUpdated   += VoiceChannelLatencyUpdated;
                    client.SpeakingUpdated  += VoiceChannelSpeakingUpdated;
                    client.StreamCreated    += VoiceChannelAudioStreamCreated;
                    client.StreamDestroyed  += VoiceChannelAudioStreamDestroyed;
                });

                CurrentVoiceChannel = voiceChannel;
                ConnectState        = UncordChannelConnectState.Connected;
            }

            return(true);
        }
Example #6
0
        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);
        }
Example #7
0
        public async Task PlayChannel(string pathOrUrl)
        {
            await Context.Message.DeleteAsync();

            //Don't do anything if never joined a voice channel
            if (VoiceInfo.PreviousVoiceChannelIndex == -1)
            {
                return;
            }

            //Load
            List <string> entries = LoadPlaylist();

            //Add new entry
            entries.Add(pathOrUrl);

            //Save
            SavePlaylist(entries);

            //Force play if theres only 1 song on queue
            if (entries.Count == 1)
            {
                List <SocketVoiceChannel> voiceChannels = Context.Guild.VoiceChannels.ToList <SocketVoiceChannel>();
                IAudioClient audioClient = await voiceChannels[VoiceInfo.PreviousVoiceChannelIndex].ConnectAsync();
                VoiceInfo.PreviousAudioClient = audioClient;
                await SendAsync(audioClient, entries[0]);
            }
        }
Example #8
0
 private async Task SendAsync(IAudioClient client, string[] path)
 {
     using (var discord = client.CreatePCMStream(AudioApplication.Voice))
     {
         foreach (var item in path)
         {
             using (var ffmpeg = GetFfmpeg(item))
                 using (var output = ffmpeg.StandardOutput.BaseStream)
                 {
                     try
                     {
                         await output.CopyToAsync(discord);
                     }
                     catch (Exception exc)
                     {
                         ffmpeg.Close();
                         output.Close();
                         await discord.FlushAsync();
                     }
                     finally
                     {
                         await discord.FlushAsync();
                     }
                 }
         }
     }
 }
Example #9
0
        internal AudioClient(IAudioClient client, WaveFormat format = null)
        {
            this.Client = client;
            this.Format = format;

            if (format == null)
            {
                IntPtr p;
                client.GetMixFormat(out p);
                format = Marshal.PtrToStructure(p, typeof(WaveFormat)) as WaveFormat;
                Marshal.FreeCoTaskMem(p);
                format = new WaveFormat(format.Channels, format.SampleRate, 16);
                var sessionId = Guid.Empty;
            }

            this.Format = format;
            try
            {
                var sessionId = Guid.Empty;
                this.Client.Initialize(AudioShareMode.Shared, AudioStreamFlags.EventCallback, 0, 0, format, ref sessionId);
            }
            catch (COMException ex)
            {
                if ((uint)ex.ErrorCode == ResultCodes.AudioClientFormatNotSupported)
                {
                    throw new WaveFormatException("Unsupported wave format.");
                }
                throw;
            }

            this.Initialize();
        }
Example #10
0
        //On Bot ready
        private async void Ready()
        {
            Print("Ready!", ConsoleColor.Green);

            //"Playing Nothing :/"
            await _client.SetGameAsync("Nothing :/");

            //Get Guilds / Servers
            try
            {
                //Server
                PrintServers();
                SocketGuild guild = _client.Guilds.FirstOrDefault(g => g.Name == Information.ServerName);

                //Text Channel
                _textChannel = guild.TextChannels.FirstOrDefault(t => t.Name == Information.TextChannelName);
                Print($"Using Text Channel: \"#{_textChannel.Name}\"", ConsoleColor.Cyan);

                //Voice Channel
                _voiceChannel = guild.VoiceChannels.FirstOrDefault(t => t.Name == Information.VoiceChannelName);
                Print($"Using Voice Channel: \"{_voiceChannel.Name}\"", ConsoleColor.Cyan);
                _audio = await _voiceChannel.ConnectAsync();
            }
            catch (Exception e)
            {
                Print("Could not join Voice/Text Channel (" + e.Message + ")", ConsoleColor.Red);
            }
        }
Example #11
0
        public async Task StartAudioInput(IAudioClient audioClient)
        {
            StartMicConnectWatcher();

            if (_AudioOutStream != null)
            {
                _AudioOutStream.Dispose();
                _AudioOutStream = null;
            }

            if (InputDeviceState != InputDeviceState.Avairable)
            {
                if (!await ResetAudioInput())
                {
                    return;
                }
            }

            _AudioOutStream = audioClient.CreatePCMStream(AudioApplication.Voice, 1920, 100);

            _FrameOutputNode.Stop();

            _AudioGraph.QuantumStarted += AudioGraph_QuantumStarted;

            _FrameOutputNode.Start();

            _AudioGraph.Start();
        }
Example #12
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);
            }
        }
Example #13
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);
        }
Example #14
0
 public VoiceConnection(IVoiceChannel voiceChannel, IAudioClient audioClient)
 {
     VoiceChannel = voiceChannel;
     AudioClient  = audioClient;
     CancelToken  = null;
     AudioStream  = AudioClient.CreatePCMStream(AudioApplication.Mixed, voiceChannel.Bitrate);
 }
Example #15
0
        public static void Initialize(IAudioClient client, ISocketMessageChannel channel)
        {
            AudioService.client  = client;
            AudioService.channel = channel;

            stream = client.CreatePCMStream(AudioApplication.Mixed);
        }
        public async Task LoadNextSong()
        {
            CurrentSong?.Stop();
            CurrentSong = null;
            if (SongQueue.Count != 0)
            {
                lock (_voiceLock) {
                    CurrentSong = SongQueue[0];
                    SongQueue.RemoveAt(0);
                }
            }
            else
            {
                Stop();
                return;
            }

            try {
                if (VoiceClient == null)
                {
                    Console.WriteLine($"Joining voice channel [{DateTime.Now.Second}]");
                    //todo add a new event, to tell people nadeko is trying to join
                    VoiceClient = await Task.Run(async() => await VoiceChannel.JoinAudio());

                    Console.WriteLine($"Joined voicechannel [{DateTime.Now.Second}]");
                }
                await Task.Factory.StartNew(async() => await CurrentSong?.Start(), TaskCreationOptions.LongRunning).Unwrap();
            }
            catch (Exception ex) {
                Console.WriteLine($"Starting failed: {ex}");
                CurrentSong?.Stop();
                CurrentSong = null;
            }
        }
Example #17
0
        private async Task Say(IAudioClient connection, ZapSound sound)
        {
            try
            {
                await connection.SetSpeakingAsync(true); // send a speaking indicator

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

                var output  = ffmpeg.StandardOutput.BaseStream;
                var discord = connection.CreatePCMStream(AudioApplication.Voice);
                await output.CopyToAsync(discord);

                await discord.FlushAsync();

                await connection.SetSpeakingAsync(false); // we're not speaking anymore
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine($"- {ex.StackTrace}");
            }
        }
Example #18
0
 public GuildAudioInfo(ITextChannel infoChannel, IAudioClient client)
 {
     InfoChannel = infoChannel;
     Client      = client;
     Ffmpeg      = null;
     Queue       = new ConcurrentQueue <string>();
 }
Example #19
0
        public async Task SkipChannel()
        {
            await Context.Message.DeleteAsync();

            //Don't do anything if never joined a voice channel
            if (VoiceInfo.PreviousVoiceChannelIndex == -1 || VoiceInfo.SkippingSong)
            {
                return;
            }

            //Load
            List <string> entries = LoadPlaylist();

            //Remove the previous played song from the queue
            if (entries.Count != 0)
            {
                entries.RemoveAt(0);
            }

            //Save
            SavePlaylist(entries);

            VoiceInfo.SkippingSong = true;

            //Play if theres any songs left on queue
            if (entries.Count != 0)
            {
                List <SocketVoiceChannel> voiceChannels = Context.Guild.VoiceChannels.ToList <SocketVoiceChannel>();
                IAudioClient audioClient = await voiceChannels[VoiceInfo.PreviousVoiceChannelIndex].ConnectAsync();
                VoiceInfo.PreviousAudioClient = audioClient;
                await SendAsync(audioClient, entries[0]);
            }
        }
Example #20
0
 /// <summary>
 /// Dispose
 /// </summary>
 public void Dispose()
 {
     if (audioClientInterface != null)
     {
         if (audioClockClient != null)
         {
             audioClockClient.Dispose();
             audioClockClient = null;
         }
         if (audioRenderClient != null)
         {
             audioRenderClient.Dispose();
             audioRenderClient = null;
         }
         if (audioCaptureClient != null)
         {
             audioCaptureClient.Dispose();
             audioCaptureClient = null;
         }
         if (audioStreamVolume != null)
         {
             audioStreamVolume.Dispose();
             audioStreamVolume = null;
         }
         Marshal.ReleaseComObject(audioClientInterface);
         audioClientInterface = null;
         GC.SuppressFinalize(this);
     }
 }
Example #21
0
        public async Task <bool> StreamToVoiceAsync(string fileName)
        {
            this._ffmpeg       = CreateStream($"{Startup.AppConfig.RootDirectory}user-intros/{fileName}");
            this._ffmpegStream = this._ffmpeg.StandardOutput.BaseStream;

            IAudioClient client = await this.ConnectAsync(this._destinationChannel.Id);

            if (client == null)
            {
                Logger.Warning($"Failed to connect to voice channel [{this._destinationChannel.Name}] in [{this.Guild.Name}]");
                Dispose();
                return(false);
            }

            this._outputStream = client.CreatePCMStream(AudioApplication.Mixed);

            try
            {
                await this._ffmpegStream.CopyToAsync(this._outputStream);
            }
            finally
            {
                await this._outputStream.FlushAsync();
                await DisconnectAsync();

                Dispose();
            }

            return(true);
        }
Example #22
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
Example #23
0
        public async Task Connect(SocketVoiceChannel voiceChannel)
        {
            if (this.audioClient != null)
            {
                await this.Disconnect();
            }
            // TRANSLATORS: Log message. In AudioManager.
            Logger.Log(T._("* Connect to voice channel"));
            try {
                // LOCK STREAMS
                await st_lock_sem.WaitAsync().ConfigureAwait(false);

                // stop recording and close audio stream
                this.CloseRecordStream();
                // TRANSLATORS: Log message. In AudioManager.
                Logger.Log(T._("- join voice channel ..."));
                this.audioClient = await voiceChannel.ConnectAsync();

                this.bitrate = voiceChannel.Bitrate;
                // create audio stream and start recording
                this.CreateRecordStream();
                // TRANSLATORS: Log message. In AudioManager.
                Logger.Log(T._("... Done!"));
            } catch (Exception e) {
                Logger.DebugLog(e.ToString());
                // TRANSLATORS: Error message. In AudioManager.
                throw new Exception(T._("Could not connect to voice channel."), e);
            } finally {
                st_lock_sem.Release();                 // RELEASE STREAMS
            }
        }
Example #24
0
        /// <summary>
        /// Tries to resolve a valid format pointer for the audio client.
        /// </summary>
        /// <param name="audioClient">The audio client to use.</param>
        /// <param name="shareMode">The share mode to use.</param>
        /// <returns>A pointer to a valid format, or zero if one cannot be found.</returns>
        public static IntPtr GetFormatPointer(IAudioClient audioClient, AUDCLNT_SHAREMODE shareMode)
        {
            var formatPtr = IntPtr.Zero;

            if (shareMode == AUDCLNT_SHAREMODE.AUDCLNT_SHAREMODE_SHARED)
            {
                audioClient.GetMixFormat(out formatPtr);
            }
            else
            {
                // Otherwise we need to find a supported format
                foreach (var format in TestWaveFormats)
                {
                    var formatMatch = IntPtr.Zero;
                    var supported   = audioClient.IsFormatSupported(shareMode, format, out formatMatch);

                    if (supported == 0)
                    {
                        formatPtr = format; break;
                    }
                    else if (supported == 1)
                    {
                        formatPtr = formatMatch; break;
                    }
                }

                if (formatPtr == IntPtr.Zero)
                {
                    Assert.Inconclusive("Unable to find a valid format pointer.");
                }
            }

            return(formatPtr);
        }
Example #25
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();
        }
Example #26
0
        public static async Task <bool> JoinChannel(string server, string channel)
        {
            SocketVoiceChannel chan = null;

            foreach (SocketVoiceChannel vchannel in getSocketChannels(server))
            {
                if (vchannel.Name == channel)
                {
                    chan = vchannel;
                }
            }

            if (chan != null)
            {
                try {
                    audioClient = await chan.ConnectAsync();

                    Log?.Invoke("Joined channel: " + chan.Name);
                } catch (Exception ex) {
                    Log?.Invoke("Error joining channel.");
                    Log?.Invoke(ex.Message);
                    return(false);
                }
            }
            return(true);
        }
Example #27
0
        private async Task Say(IAudioClient connection, string sound, SocketVoiceChannel channel)
        {
            try
            {
                await connection.SetSpeakingAsync(true); // send a speaking indicator

                var psi = new ProcessStartInfo
                {
                    FileName  = "ffmpeg",
                    Arguments = $@"-re -i ""audio/{sound}.wav"" -ac 2 -f s16le -ar 48000 pipe:1",
                    RedirectStandardOutput = true,
                    UseShellExecute        = false
                };
                var ffmpeg = Process.Start(psi);

                var output = ffmpeg.StandardOutput.BaseStream;
                Tuple <IAudioClient, Process> t = new Tuple <IAudioClient, Process>(connection, ffmpeg);
                _connections[channel.Guild.Id] = t;
                var discord = connection.CreatePCMStream(AudioApplication.Voice);
                await output.CopyToAsync(discord);

                await discord.FlushAsync();

                Tuple <IAudioClient, Process> te = new Tuple <IAudioClient, Process>(connection, null);
                _connections[channel.Guild.Id] = te;
                await connection.SetSpeakingAsync(false); // we're not speaking anymore
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine($"- {ex.StackTrace}");
            }
        }
Example #28
0
        public async Task LoadNextSong() {
            CurrentSong?.Stop();
            CurrentSong = null;
            if (SongQueue.Count != 0) {
                CurrentSong = SongQueue[0];
                SongQueue.RemoveAt(0);
            } else {
                VoiceClient?.Disconnect();
                VoiceClient = null;
                return;
            }

            try {
                if (VoiceClient == null) {
                    Console.WriteLine($"Joining voice channel [{DateTime.Now.Second}]");
                    //todo add a new event, to tell people nadeko is trying to join
                    VoiceClient = await VoiceChannel.JoinAudio();
                    Console.WriteLine($"Joined voicechannel [{DateTime.Now.Second}]");
                }
                await Task.Factory.StartNew(async () => await CurrentSong?.Start(), TaskCreationOptions.LongRunning).Unwrap();
            } catch (Exception ex) {
                Console.WriteLine($"Starting failed: {ex}");
                CurrentSong?.Stop();
                CurrentSong = null;
            }
        }
Example #29
0
        //[Command("come",RunMode =RunMode.Async)]
        //[Summary("Comes joins to the channel")]
        public async Task Come()
        {
            try
            {
                _audio?.Dispose();

                _voiceChannel = Context.Guild.GetVoiceChannelsAsync(CacheMode.AllowDownload).Result.FirstOrDefault(x => x.Name.ToLower() == "Music".ToLower());

                if (_voiceChannel == null)
                {
                    await Context.Channel.SendMessageAsync("Create a Voice Channel with the name Music");
                }
                _textChannel = Context.Guild.GetTextChannelsAsync(CacheMode.AllowDownload).Result.FirstOrDefault(x => x.Name.ToLower() == "Music".ToLower());
                if (_textChannel == null)
                {
                    await Context.Channel.SendMessageAsync("Create a Text Channel with the name Music");
                }

                _audio = await _voiceChannel.ConnectAsync();
            }
            catch (Exception ex)
            {
                CommonTools.ErrorReporting(ex);
            }
        }
Example #30
0
        public async Task Disconnect()
        {
            // TRANSLATORS: Log message. In AudioManager.
            Logger.Log(T._("* Disconnect from voice channel"));
            try {
                await st_lock_sem.WaitAsync().ConfigureAwait(false);                 // LOCK STREAMS

                // stop recording and close audio stream
                this.CloseRecordStream();
                // leave voice chat
                if (this.audioClient != null)
                {
                    // TRANSLATORS: Log message. In AudioManager.
                    Logger.Log(T._("- leave voice channel ..."));
                    await this.audioClient.StopAsync();

                    this.audioClient.Dispose();
                    this.audioClient = null;
                }
                else
                {
                    // TRANSLATORS: Log message. In AudioManager.
                    Logger.Log(T._("- not in voice channel."));
                }
                // TRANSLATORS: Log message. In AudioManager.
                Logger.Log(T._("... Done!"));
            } catch (Exception e) {
                Logger.DebugLog(e.ToString());
                // TRANSLATORS: Error message. In AudioManager.
                throw new Exception(T._("Could not disconnect from voice channel."), e);
            } finally {
                st_lock_sem.Release();                 // RELEASE STREAMS
            }
        }
Example #31
0
        public async Task PlayStartSound(IAudioClient audioClient)
        {
            var preCountdownSound = new Random().Next(1, 7).ToString().PadLeft(3, '0');

            await ExecuteSound(audioClient, preCountdownSound);
            await ExecuteSound(audioClient, "start");
        }
Example #32
0
 public void Dispose()
 {
     try { Stop(); } catch { }
     lock (mutex)
     {
         Cleanup();
         if (audioClient != null)
         {
             Marshal.ReleaseComObject(audioClient); audioClient = null;
         }
         if (endpoint != null)
         {
             Marshal.ReleaseComObject(endpoint); endpoint = null;
         }
         if (enumerator != null)
         {
             Marshal.ReleaseComObject(enumerator); enumerator = null;
         }
         isInited = false;
         buffers  = null;
         thread   = null;
         i8Buf    = null; i16Buf = null;
         i32Buf   = null; f32Buf = null;
         f64Buf   = null;
     }
 }
Example #33
0
        private Task RunQueueAsync()
        {
            new TaskFactory().StartNew(async() =>
            {
                while (true)
                {
                    try
                    {
                        Track currentTrack;
                        if (Queue.TryDequeue(out currentTrack))
                        {
                            playingTrack = currentTrack;
                            try { await audioClient.StopAsync().ConfigureAwait(false); } catch { Log.Message(LogSeverity.Warning, "MusicPlayer.cs: Unable to Stop Audio Client"); }
                            audioClient = await playingTrack.sourceVoiceChannel.ConnectAsync();
                            if (audioClient != null)
                            {
                                try { await LumpiBot.Client.SetGameAsync(playingTrack.SourceVideo.Title); } catch { }

                                await StreamAsync(playingTrack).ConfigureAwait(true);
                            }
                        }
                    }
                    finally
                    {
                        await Task.Delay(1000);
                    }
                }
            });

            return(Task.CompletedTask);
        }
Example #34
0
        internal void Stop() {
            Stopped = true;
            SongQueue.Clear();
            CurrentSong?.Stop();
            CurrentSong = null;
            VoiceClient?.Disconnect();
            VoiceClient = null;

            MusicControls throwAwayValue;
            MusicModule.musicPlayers.TryRemove(_e.Server, out throwAwayValue);
        }
Example #35
0
        public void Start(IAudioClient a_Client)
        {
            if (playbackState == StreamingPlaybackState.Stopped)
            {
                playbackState = StreamingPlaybackState.Buffering;

                _client = a_Client;

                Task.Run(() => { Stream(a_Client); });
            }
            else if (playbackState == StreamingPlaybackState.Paused)
            {
                playbackState = StreamingPlaybackState.Buffering;
            }
        }
Example #36
0
        public static async Task ExecutePlaylist(IAudioClient voiceClient, List<string> playlist, Channel jamSessionChatChannel)
        {
            while (playlist.Count > 0)
            {
                string strCmdText;
                // TODO: Make this better
                Process cmdProcess = new Process();
                cmdProcess.StartInfo.FileName = "cmd.exe";
                cmdProcess.StartInfo.UseShellExecute = false;
                cmdProcess.StartInfo.RedirectStandardOutput = true;
                cmdProcess.StartInfo.RedirectStandardInput = true;
                cmdProcess.Start();

                /* Change for local/prod */
                //cmdProcess.StandardInput.WriteLine(@"del C:\Users\Tony\Desktop\Misc\DiscordBot\DiscordMusicBot\DiscordMusicBot\bin\assets\current.mp3");
                cmdProcess.StandardInput.WriteLine(@"del C:\MilliaBot\MilliaBot\assets\current.mp3");

                //cmdProcess.StartInfo.WorkingDirectory = @"cd C:\Users\Tony\Desktop\Misc\DiscordBot\DiscordMusicBot\DiscordMusicBot\bin\Debug";
                cmdProcess.StartInfo.WorkingDirectory = @"cd C:\MilliaBot\MilliaBot\Debug";

                strCmdText =
                    "youtube-dl -o ../assets/current.mp3 --extract-audio --audio-format mp3 " +
                    playlist.First();
                cmdProcess.StandardInput.WriteLine(strCmdText);

                await Task.Delay(5555);

                string file = "../assets/current.mp3";

                await jamSessionChatChannel.SendMessage("Now playing: " + playlist.First());
                if (playlist.Count > 1)
                {
                    await jamSessionChatChannel.SendMessage("Songs left in the playlist: " + playlist.Count);
                }

                await PlayMusic(voiceClient, file);

                if (playlist.Count > 0)
                    playlist.RemoveAt(0);
            }
        }
Example #37
0
        public override async void ShowDialog()
        {
            LoginDialog dialog = new LoginDialog();

            if (dialog.ShowDialog() == true)
            {
                _client = new DiscordClient();
                _client.UsingAudio(x =>
                {
                    x.Mode = AudioMode.Outgoing;
                    x.Bitrate = null;
                    x.Channels = 2;
                });

                await _client.Connect(dialog.Username, dialog.Password);
                var voiceChannel = CurrentServer.VoiceChannels.FirstOrDefault(d => d.Name == "Bot Test");

                _voiceClient = await _client.GetService<AudioService>()
                    .Join(voiceChannel);
            }
        }
Example #38
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();
        }
Example #39
0
 internal AudioOutputClient(IAudioClient client, WaveFormat format)
     : base(client, format)
 {
     _render = this.GetService<IAudioRenderClient>();
 }
Example #40
0
 internal AudioClient(IAudioClient realClient)
 {
     _RealClient = realClient;
 }
Example #41
0
        private void Stream(IAudioClient client)
        {
            IMp3FrameDecompressor decompressor = null;

            ShoutcastStream shoutStream = new ShoutcastStream(server);
            shoutStream.StreamTitleChanged += ChangedTitle;
            var buffer = new byte[16384 * 4]; // needs to be big enough to hold a decompressed frame

            try
            {
                    do
                    {

                        if (IsBufferNearlyFull)
                        {
                            Console.WriteLine("Buffer getting full, taking a break");
                            Thread.Sleep(500);
                        }
                        else
                        {
                            Mp3Frame frame;
                            try
                            {
                                frame = Mp3Frame.LoadFromStream(shoutStream);
                            }
                            catch (EndOfStreamException)
                            {
                                fullyDownloaded = true;
                                // reached the end of the MP3 file / stream
                                break;
                            }
                            catch (WebException)
                            {
                                // probably we have aborted download from the GUI thread
                                break;
                            }
                            if (decompressor == null)
                            {
                                // don't think these details matter too much - just help ACM select the right codec
                                // however, the buffered provider doesn't know what sample rate it is working at
                                // until we have a frame
                                decompressor = CreateFrameDecompressor(frame);
                                bufferedWaveProvider = new BufferedWaveProvider(decompressor.OutputFormat);
                                bufferedWaveProvider.BufferDuration = TimeSpan.FromSeconds(20); // allow us to get well ahead of ourselves
                            }
                            int decompressed = decompressor.DecompressFrame(frame, buffer, 0);
                            bufferedWaveProvider.AddSamples(buffer, 0, decompressed);
                        }

                        if (bufferedWaveProvider != null)
                        {
                            var bufferedSeconds = bufferedWaveProvider.BufferedDuration.TotalSeconds;

                            if (bufferedSeconds > 4 && playbackState == StreamingPlaybackState.Buffering)
                            {
                                playbackState = StreamingPlaybackState.Playing;
                                Task.Run(() => { StartPlay(); });
                            }
                            else if (fullyDownloaded && bufferedSeconds == 0)
                            {
                                Console.WriteLine("Reached end of stream");
                                Stop();
                            }
                        }
                    } while (playbackState != StreamingPlaybackState.Stopped);
            
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (decompressor != null)
                {
                    decompressor.Dispose();
                }
            }
        }
Example #42
0
        public async Task Play(IAudioClient voiceClient, CancellationToken cancelToken)
        {
            var filename = Path.Combine(Music.MusicDataPath, DateTime.Now.UnixTimestamp().ToString());

            SongBuffer inStream = new SongBuffer(MusicPlayer, filename, SongInfo, skipTo, frameBytes * 100);
            var bufferTask = inStream.BufferSong(cancelToken).ConfigureAwait(false);

            bytesSent = 0;

            try
            {
                var attempt = 0;             

                var prebufferingTask = CheckPrebufferingAsync(inStream, cancelToken, 1.MiB()); //Fast connection can do this easy
                var finished = false;
                var count = 0;
                var sw = new Stopwatch();
                var slowconnection = false;
                sw.Start();
                while (!finished)
                {
                    var t = await Task.WhenAny(prebufferingTask, Task.Delay(2000, cancelToken));
                    if (t != prebufferingTask)
                    {
                        count++;
                        if (count == 10)
                        {
                            slowconnection = true;
                            prebufferingTask = CheckPrebufferingAsync(inStream, cancelToken, 20.MiB());
                            _log.Warn("Slow connection buffering more to ensure no disruption, consider hosting in cloud");
                            continue;
                        }
                        
                        if (inStream.BufferingCompleted && count == 1)
                        {
                            _log.Debug("Prebuffering canceled. Cannot get any data from the stream.");
                            return;
                        }
                        else
                        {
                            continue;
                        }
                     }
                    else if (prebufferingTask.IsCanceled)
                    {
                        _log.Debug("Prebuffering canceled. Cannot get any data from the stream.");
                        return;
                    }
                    finished = true;
                }
                sw.Stop();
                _log.Debug("Prebuffering successfully completed in "+ sw.Elapsed);

                var outStream = voiceClient.CreatePCMStream(960);

                int nextTime = Environment.TickCount + milliseconds;

                byte[] buffer = new byte[frameBytes];
                while (!cancelToken.IsCancellationRequested)
                {
                    //Console.WriteLine($"Read: {songBuffer.ReadPosition}\nWrite: {songBuffer.WritePosition}\nContentLength:{songBuffer.ContentLength}\n---------");
                    var read = await inStream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);
                    //await inStream.CopyToAsync(voiceClient.OutputStream);
                    if(read < frameBytes)
                        _log.Debug("read {0}", read);
                    unchecked
                    {
                        bytesSent += (ulong)read;
                    }
                    if (read < frameBytes)
                    {
                        if (read == 0)
                        {
                            if (inStream.BufferingCompleted)
                                break;
                            if (attempt++ == 20)
                            {
                                MusicPlayer.SongCancelSource.Cancel();
                                break;
                            }
                            if (slowconnection)
                            {
                                _log.Warn("Slow connection has disrupted music, waiting a bit for buffer");
                                await Task.Delay(1000, cancelToken).ConfigureAwait(false);
                            }
                            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);
                    if (read != frameBytes) continue;
                    nextTime = unchecked(nextTime + milliseconds);
                    int delayMillis = unchecked(nextTime - Environment.TickCount);
                    if (delayMillis > 0)
                        await Task.Delay(delayMillis, cancelToken).ConfigureAwait(false);
                    await outStream.WriteAsync(buffer, 0, read).ConfigureAwait(false);
                }
            }
            finally
            {
                await bufferTask;
                if(inStream != null)
                    inStream.Dispose();
            }
        }
Example #43
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;
                    });
            });
        }
Example #44
0
        private void InitializeCaptureDevice(IAudioClient audioClientInterface)
        {
            var audioClient = new AudioClient((IAudioClient)audioClientInterface);
            if (waveFormat == null)
            {                
                this.waveFormat = audioClient.MixFormat;
            }         

            long requestedDuration = REFTIMES_PER_MILLISEC * 100;

            
            if (!audioClient.IsFormatSupported(AudioClientShareMode.Shared, WaveFormat))
            {
                throw new ArgumentException("Unsupported Wave Format");
            }
            
            var streamFlags = GetAudioClientStreamFlags();

            audioClient.Initialize(AudioClientShareMode.Shared,
                streamFlags,
                requestedDuration,
                0,
                this.waveFormat,
                Guid.Empty);
           

            int bufferFrameCount = audioClient.BufferSize;
            this.bytesPerFrame = this.waveFormat.Channels * this.waveFormat.BitsPerSample / 8;
            this.recordBuffer = new byte[bufferFrameCount * bytesPerFrame];
            Debug.WriteLine(string.Format("record buffer size = {0}", this.recordBuffer.Length));

            // Get back the effective latency from AudioClient
            latencyMilliseconds = (int)(audioClient.StreamLatency / 10000);
        }
Example #45
0
            public async Task StartPlaylist()
            {
                if (IsPlaying) return;

                if (await IsPlaylistEmpty())
                    return;

                if (PlaybackChannel == null)
                {
                    await ChatChannel.SafeSendMessage("Audio playback channel has not been set.");
                    return;
                }

                if (!await DiscordUtils.CanJoinAndTalkInVoiceChannel(PlaybackChannel, ChatChannel))
                    return;

                _voiceClient = await _client.Audio().Join(PlaybackChannel);

                while (true)
                {
                    if (_stopPlaylistFlag)
                    {
                        _stopPlaylistFlag = false;
                        break;
                    }

                    if (await IsPlaylistEmpty())
                        return;

                    await StartCurrentTrackPlayback();

                    if (_prevFlag)
                    {
                        _prevFlag = false;
                        TrackIndex--;
                    }
                    else if (!_skipToFlag)
                        TrackIndex++;
                }

                _voiceClient.Wait();
                await _voiceClient.Disconnect();
            }
Example #46
0
 public AudioClient(IAudioClient client)
 {
     _audioClient = client;
 }
Example #47
0
 internal AudioClient(IAudioClient audioClientInterface)
 {
     this.audioClientInterface = audioClientInterface;
 }
Example #48
0
 internal AudioInputClient(IAudioClient client, WaveFormat format)
     : base(client, format)
 {
     _capture = this.GetService<IAudioCaptureClient>();
 }
Example #49
0
        private static async void Bot_MessagedReceived(object sender, MessageEventArgs e)
        {
            if (e.Message.IsAuthor) return;

            //help cmd
            string[] cmds = {"!help", "!ping", "!yt <search term>", "!img <search term>", "!8ball <question>", "!roll", "!bass" };
            if (e.Message.Text.ToLower().Equals(prefix + "help"))
            {
                string cmdStringer = e.User.Mention + "\n__**Commands:**__";
                foreach (string s in cmds)
                {
                    cmdStringer += "\n\t- " + s;
                }
                await e.Channel.SendMessage(cmdStringer);
            }
            //ping cmd
            else if (e.Message.Text.ToLower().Equals(prefix + "ping"))
            {
                await e.Channel.SendMessage(e.User.Mention + " Pong");
            }
            //yt cmd
            else if (e.Message.Text.ToLower().Contains(prefix + "yt") && e.Message.Text.IndexOf(prefix) == 0)
            {
                ytSearch = e.Message.Text.Remove(0, 3);
                if (String.IsNullOrWhiteSpace(ytSearch))
                {
                    await e.Channel.SendMessage(e.User.Mention + " Your command must have a search term attached to it! Use \"!help\" for assistance.");
                }
                else
                {
                    new Program().YoutubeMethod().Wait();
                    await e.Channel.SendMessage(e.User.Mention + " " + ytResult);
                }
            }
            //image cmd
            else if (e.Message.Text.ToLower().Contains(prefix + "img") && e.Message.Text.IndexOf(prefix) == 0)
            {
                string searchTerm = e.Message.Text.Remove(0, 5);
                if (String.IsNullOrWhiteSpace(searchTerm))
                {
                    await e.Channel.SendMessage(e.User.Mention + " Your command must have a search term attached to it! Use \"!help\" for assistance.");
                }
                else
                {

                    var bing = new BingSearchContainer(
                        new Uri("https://api.datamarket.azure.com/Bing/Search/"))
                    { Credentials = new NetworkCredential(bingSearchKey, bingSearchKey) };

                    var query = bing.Image(searchTerm, "EnableHighlighting", "en-US", "Moderate", null, null, null);
                    var results = query.Execute();

                    ImageResult[] aResults = results.ToArray<ImageResult>();

                    int index = r.Next(0, aResults.Length);
                    ImageResult item = aResults[index];

                    await e.Channel.SendMessage(e.User.Mention + " " + item.MediaUrl);
                }
            }
            //8ball cmd
            else if (e.Message.Text.ToLower().Contains(prefix + "8ball") && e.Message.Text.IndexOf(prefix) == 0)
            {
                string question = e.Message.Text.Remove(0, 6);
                if (string.IsNullOrWhiteSpace(question))
                {
                    await e.Channel.SendMessage(e.User.Mention + " Your command must have a question attached to it! Use \"!help\" for assistance.");
                    return;
                }

                string[] responses = {"Not likely.", "More than likely"};
                int index = r.Next(0, responses.Length);
                await e.Channel.SendMessage(e.User.Mention + " " + responses[index]);
            }
            //roll cmd
            else if (e.Message.Text.ToLower().Equals(prefix + "roll"))
            {
                int face = r.Next(1, 7);
                await e.Channel.SendMessage(e.User.Mention + " Rolled a " + face);
                switch (face)
                {
                    case 1:
                        await e.Channel.SendFile("Assets/Dice/dice1.png");
                        break;
                    case 2:
                        await e.Channel.SendFile("Assets/Dice/dice2.png");
                        break;
                    case 3:
                        await e.Channel.SendFile("Assets/Dice/dice3.png");
                        break;
                    case 4:
                        await e.Channel.SendFile("Assets/Dice/dice4.png");
                        break;
                    case 5:
                        await e.Channel.SendFile("Assets/Dice/dice5.png");
                        break;
                    case 6:
                        await e.Channel.SendFile("Assets/Dice/dice6.png");
                        break;
                    default:
                        await e.Channel.SendFile("Assets/Dice/dice1.png");
                        break;
                }
            }
            //bass cmd
            else if (e.Message.Text.ToLower().Equals(prefix + "bass"))
            {
                if (e.User.VoiceChannel != null)
                {
                    //set up
                    bot.UsingAudio(x =>
                    {
                        x.Mode = AudioMode.Outgoing;
                    });

                    //joining a channel
                    var voiceChannel = bot.FindServers("Bot Testing Place").FirstOrDefault().VoiceChannels.FirstOrDefault();
                    _vClient = await bot.GetService<AudioService>().Join(voiceChannel);

                    SendAudio("Assets/Audio/bass.mp3");


                }
                else
                {
                    await e.Channel.SendMessage(e.User.Mention + " You must be in a voice room to do this. Use \"!help\" for assistance.");
                }
            }

        }
Example #50
0
        public void Start()
        {
            Console.WriteLine("Initializing...");
            _client = new DiscordClient();

            _client.UsingAudio(x => // Opens an AudioConfigBuilder so we can configure our AudioService
            { x.Mode = AudioMode.Outgoing; // Tells the AudioService that we will only be sending audio
            });

            // _vClient = _client.GetService<AudioService>();

            _client.MessageReceived += async (s, e) =>
            {
                if (!e.Message.IsAuthor)
                {
                    Console.WriteLine(e.Message.User.Name + "> " + e.Message.Text);
                    if (e.Message.Text.StartsWith("!!"))
                    {
                        string command = e.Message.Text.Replace("!!", "");
                        //   if (command.Equals(""))
                        //      {
                        //                 await e.Channel.SendMessage("I am Jukebot. Do !!info for more details.");
                        //
                        //          }
                        string[] words = command.Split(' ');
                        switch (words[0])
                        {
                            case "info":
                                await
                                    e.Channel.SendMessage(
                                        "```diff\n!====== [Jukebot] ======!" +
                                        "\nA shitty ass music bot made by Ratismal (stupid cat)" +
                                        "\nIt plays music. lol what did u expect" +
                                        "\n!== [Features] ==!" +
                                        "\n+ a shitty looking unintuitive piece of shit GUI that only the host can see (lol)" +
                                        "\n+ plays music" +
                                        "\n!== [Commands] ==!" +
                                        "\n+ !!info - shows this" +
                                        "\n+ !!summon - summons bot to current voice channel" +
                                        "\n+ !!banish - tells the bot to piss off" +
                                        "\n+ !!volume - shows the current volume" +
                                        "\n+ !!volume <amount> - set the volume" +
                                        "\n+ !!volume +-<amount> - add/subtract the volume" +
                                        "\n!== [Conclusi] ==!" +
                                        "\n+ '-on' cut off from title for consistancy spacing sake" +
                                        "\n+ f**k my life" +
                                        "\n+ you want to play something? GOOD LUCK WITH THAT LOL ONLY I CAN" +
                                        "\n- This is red text!" +
                                        "\n- its really late i should go to bed lol fml smfh lmao kms" +
                                        "\n```");
                                break;
                            case "summon":
                                Console.WriteLine("Joining a voice channel");
                                await e.Channel.SendMessage("Joining channel");
                                var voiceChannel = e.User.VoiceChannel;
                                _vClient = await _client.GetService<AudioService>().Join(voiceChannel);
                                //await _vClient.Join(voiceChannel);
                                break;
                            case "banish":
                                Console.WriteLine("Leaving a voice channel");

                                await e.Channel.SendMessage("Leaving channel");
                                await _client.GetService<AudioService>().Leave(e.Server);
                                break;
                            case "volume":
                                if (words.Length == 1)
                                {
                                    e.Channel.SendMessage("Current volume: " + MainWindow.volume);
                                }
                                else
                                {
                                    //  string goodstuff;
                                    if (words[1].StartsWith("+") || words[1].StartsWith("-"))
                                    {
                                        int addVolume = Int32.Parse(words[1]);
                                        MainWindow.volume += addVolume;
                                        e.Channel.SendMessage("New volume: " + MainWindow.volume);
                                    }
                                    else
                                    {
                                        MainWindow.volume = Int32.Parse(words[1]);
                                        e.Channel.SendMessage("New volume: " + MainWindow.volume);
                                    }
                                }

                                break;
                            default:
                                await e.Channel.SendMessage("I am Jukebot. Do !!info for more details.");
                                break;
                        }
                    }
                }
            };

            _client.ExecuteAndWait(async () =>
            {
                await
                    _client.Connect(token
                        );
            });
            Console.WriteLine("Cool story bro (finished)");
        }
Example #51
0
 /// <summary>
 /// Dispose
 /// </summary>
 public void Dispose()
 {
     if (audioClientInterface != null)
     {
         if (audioRenderClient != null)
         {
             audioRenderClient.Dispose();
             audioRenderClient = null;
         }
         if (audioCaptureClient != null)
         {
             audioCaptureClient.Dispose();
             audioCaptureClient = null;
         }
         Marshal.ReleaseComObject(audioClientInterface);
         audioClientInterface = null;
         GC.SuppressFinalize(this);
     }
 }
Example #52
0
File: Song.cs Project: Ryonez/Lucy
        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();
            }
        }
Example #53
0
 //TODO: This isn't threadsafe
 internal async Task RemoveClient(Server server, IAudioClient client)
 {
     if (Config.EnableMultiserver && server != null)
     {
         if (_voiceClients.TryRemove(server.Id, out client))
         {
             await client.Disconnect();
             await (client as AudioClient).GatewaySocket.Disconnect();
         }
     }
 }
Example #54
0
 //TODO: This isn't threadsafe
 internal void RemoveClient(Server server, IAudioClient client)
 {
     if (Config.EnableMultiserver && server != null)
         _voiceClients.TryRemove(server.Id, out client);
 }