summaryrefslogtreecommitdiff
path: root/DiscoBot/AudioService.cs
diff options
context:
space:
mode:
authorTrueDoctor <d-kobert@web.de>2018-04-08 23:06:21 +0200
committerTrueDoctor <d-kobert@web.de>2018-04-08 23:06:21 +0200
commitcac1ade8763605c3cf09859a48358cab0e00027a (patch)
treea25658e2f59964facb7db25ed7d4056c072f2be6 /DiscoBot/AudioService.cs
parent23d2ede6124b0a7b10a74058a396477d52941337 (diff)
Added Audio Support
Diffstat (limited to 'DiscoBot/AudioService.cs')
-rw-r--r--DiscoBot/AudioService.cs88
1 files changed, 88 insertions, 0 deletions
diff --git a/DiscoBot/AudioService.cs b/DiscoBot/AudioService.cs
new file mode 100644
index 0000000..bb4d21e
--- /dev/null
+++ b/DiscoBot/AudioService.cs
@@ -0,0 +1,88 @@
+using System.Collections.Concurrent;
+using System.Diagnostics;
+using System.IO;
+using System.Threading.Tasks;
+using Discord;
+using Discord.Audio;
+
+namespace DiscoBot
+{
+ public class AudioService
+ {
+ private readonly ConcurrentDictionary<ulong, IAudioClient> ConnectedChannels =
+ new ConcurrentDictionary<ulong, IAudioClient>();
+
+ public async Task JoinAudio(IGuild guild, IVoiceChannel target)
+ {
+ IAudioClient client;
+ if (ConnectedChannels.TryGetValue(guild.Id, out client))
+ {
+ return;
+ }
+
+ if (target.Guild.Id != guild.Id)
+ {
+ return;
+ }
+
+ var audioClient = await target.ConnectAsync();
+
+ if (ConnectedChannels.TryAdd(guild.Id, audioClient))
+ {
+ // If you add a method to log happenings from this service,
+ // you can uncomment these commented lines to make use of that.
+ //await Log(LogSeverity.Info, $"Connected to voice on {guild.Name}.");
+ }
+ }
+
+ public async Task LeaveAudio(IGuild guild)
+ {
+ IAudioClient client;
+ if (ConnectedChannels.TryRemove(guild.Id, out client))
+ {
+ await client.StopAsync();
+ //await Log(LogSeverity.Info, $"Disconnected from voice on {guild.Name}.");
+ }
+ }
+
+ public async Task SendAudioAsync(IGuild guild, IMessageChannel channel, string path)
+ {
+ // Your task: Get a full path to the file if the value of 'path' is only a filename.
+ if (!File.Exists(path))
+ {
+ await channel.SendMessageAsync("File does not exist.");
+ return;
+ }
+
+ IAudioClient client;
+ if (ConnectedChannels.TryGetValue(guild.Id, out client))
+ {
+ //await Log(LogSeverity.Debug, $"Starting playback of {path} in {guild.Name}");
+ using (var ffmpeg = Process.Start(path))
+ using (var stream = client.CreatePCMStream(AudioApplication.Music))
+ {
+ try
+ {
+ await ffmpeg.StandardOutput.BaseStream.CopyToAsync(stream);
+ }
+ finally
+ {
+ await stream.FlushAsync();
+ }
+ }
+ }
+ }
+
+ private Process CreateStream(string path)
+ {
+ return Process.Start(
+ new ProcessStartInfo
+ {
+ FileName = "ffmpeg.exe",
+ Arguments = $"-hide_banner -loglevel panic -i \"{path}\" -ac 2 -f s16le -ar 48000 pipe:1",
+ UseShellExecute = false,
+ RedirectStandardOutput = true
+ });
+ }
+ }
+}