Skip to content

Instantly share code, notes, and snippets.

@Joe4evr
Last active February 27, 2025 23:17
Show Gist options
  • Select an option

  • Save Joe4evr/773d3ce6cc10dbea6924d59bbfa3c62a to your computer and use it in GitHub Desktop.

Select an option

Save Joe4evr/773d3ce6cc10dbea6924d59bbfa3c62a to your computer and use it in GitHub Desktop.
D.Net 1.0 audio example
using System.Threading.Tasks;
using Discord.Commands;
public class AudioModule : ModuleBase<ICommandContext>
{
// Scroll down further for the AudioService.
// Like, way down
private readonly AudioService _service;
// Remember to add an instance of the AudioService
// to your IServiceCollection when you initialize your bot
public AudioModule(AudioService service)
{
_service = service;
}
// You *MUST* mark these commands with 'RunMode.Async'
// otherwise the bot will not respond until the Task times out.
[Command("join", RunMode = RunMode.Async)]
public async Task JoinCmd()
{
await _service.JoinAudio(Context.Guild, (Context.User as IVoiceState).VoiceChannel);
}
// Remember to add preconditions to your commands,
// this is merely the minimal amount necessary.
// Adding more commands of your own is also encouraged.
[Command("leave", RunMode = RunMode.Async)]
public async Task LeaveCmd()
{
await _service.LeaveAudio(Context.Guild);
}
[Command("play", RunMode = RunMode.Async)]
public async Task PlayCmd([Remainder] string song)
{
await _service.SendAudioAsync(Context.Guild, Context.Channel, song);
}
}
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using Discord;
using Discord.Audio;
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 = CreateProcess(path))
using (var stream = client.CreatePCMStream(AudioApplication.Music))
{
try { await ffmpeg.StandardOutput.BaseStream.CopyToAsync(stream); }
finally { await stream.FlushAsync(); }
}
}
}
private Process CreateProcess(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
});
}
}
@stevenjw01

stevenjw01 commented Jan 27, 2018

Copy link
Copy Markdown

@Flysenberg I am still having trouble with the AudioService. Can you explain more? Maybe with an example. That would help a lot! Thanks.
I get "Failed to create "AudioModule", dependency "AudioService" was not found."

@Scags

Scags commented Mar 12, 2018

Copy link
Copy Markdown

@3NdR1m may be a bit late but you have to rename "libopus.dll" to "opus.dll" in order for the bot to stay in the channel.

@Straafe

Straafe commented Apr 8, 2018

Copy link
Copy Markdown

I'm getting CreateProcess does not exist exist in current context. (line 56 of AudioService)

ghost commented Apr 22, 2018

Copy link
Copy Markdown

Probably meant to be CreateStream

@Donad678

Donad678 commented May 6, 2018

Copy link
Copy Markdown

even when i add AudioService to Service Collection i get an error that Audio Service was not found (i'm using discord.net-2.0.0-beta2-00936)

@cheessecake

Copy link
Copy Markdown

I think I have all this set up, and when the bot joins the voice channel the console says A MessageReceived handler is blocking the gateway task. After about 30 seconds it disconnects and says The operation has timed out. Anyone know why it does this?

@FabioGNR

Copy link
Copy Markdown

@cheessecake I had the same issue and my issue was that I was connecting on the GuildAvailable event, while this is before the Ready event.
Apparently connecting should be done after the ready event so now that I Connect to the voice channel there I'm no longer seeing that problem, though I do have another problem when it's loading the opus DLL but that's something else.

@famattsson

famattsson commented Jun 3, 2018

Copy link
Copy Markdown

I can get my bot to join the voice channel. However, it does not play any audio when i run the play command. The file is found and there are no exceptions. The execution seems to stop on await ffmpeg.StandardOutput.BaseStream.CopyToAsync(stream);

@JoaoBCoelho

Copy link
Copy Markdown

To fix the "bot manages to join my voice channel but leaves almost instantly problem" I:

Renamed libopus.dll to opus.dll
Renamed libopus.dll.checksums to opus.dll.checksums
Opened the opus.dll.checksums and replaced "libopus.dll" to "opus.dll"
Debug: any CPU to x64

I hope this helps

@arekminajj

Copy link
Copy Markdown

Hi! I got an error The name "CreateProcess" does not exist in the current context. Do someone know how to solve that?

@IbenLeurs

IbenLeurs commented Jun 21, 2018

Copy link
Copy Markdown

I'm using a bot with json files and I don't use a serviceprovider, so where should I add the AudioService instead?
program

@IbenLeurs

Copy link
Copy Markdown

@Arek123113 if the error in the AudioService, you need to change it to CreateStream

@gamerchamper

Copy link
Copy Markdown

does nothing please help

@jakbrtz

jakbrtz commented Jul 29, 2018

Copy link
Copy Markdown

Thanks for posting this, it's been really helping.
When I play a file shorter than 5 seconds, it causes the next file to mute for the same amount of time as the duration of the first file. My current fix is to make the bot leave and join the channel, but I was wondering if anyone knew a better solution?

@viewless

viewless commented Nov 18, 2018

Copy link
Copy Markdown

Hello, I don't know why this doesn't work for me. I haven't changed anything from the code given. I just created Main https://pastebin.com/L91CfnWE the bot responds to the message command I made but not to audio commands. Can someone help me?

@cheessecake

Copy link
Copy Markdown

Is there a way to let this play YouTube music?

@Assemblyx86

Copy link
Copy Markdown

Hello. in "AudioModule.cs", Line 20("private readonly AudioService _service;"). The "AudioService" is underlined red saying that I am missing a directive or assembly reference. I am using all the directives in this code posted here and yet I'm still getting that error, What namespace is "AudioService" in?

@KitsuneAndCake

Copy link
Copy Markdown

Hello. in "AudioModule.cs", Line 20("private readonly AudioService _service;"). The "AudioService" is underlined red saying that I am missing a directive or assembly reference. I am using all the directives in this code posted here and yet I'm still getting that error, What namespace is "AudioService" in?

I believe it's just using Discord.
Add: using Discord and it should work, I believe.

@Mikusho

Mikusho commented Dec 22, 2020

Copy link
Copy Markdown

How to Stream desktop audio??

@aggiczy

aggiczy commented Feb 28, 2021

Copy link
Copy Markdown

My bot joins and then instantly disconnects from the voice channel. How do I fix this?

Same. How do I fix this?

@Mikusho

Mikusho commented Feb 28, 2021 via email

Copy link
Copy Markdown

@ABeer905

ABeer905 commented Mar 24, 2021

Copy link
Copy Markdown

I can only get the audio to play once following the SendAudioAsync method. When I call the audio command again the bot lights up green as if it were talking but no audio comes through. In order to play the audio file again the bot has to leave and rejoin. Any ideas?

@Nessitro

Copy link
Copy Markdown

@Sombody101

Copy link
Copy Markdown

Can we start making a more updated version of this? I say we, but I don't really know what I'm doing.
I used this tutorial to try and make a music bot, but it didn't work. I'm not sure if that's because the libraries aren't set up right, or because I'm feeding it .mp3 files. But it no workie, and I can't find any other tutorials.
I did what the tutorial said and renamed one of the .dll files, and placed both inside my bin/debug folder (Strange that you don't want to reference it, unless FFmpeg does on its own. I'm not sure), and it didn't do anything. I think I would have felt better if it threw an error so I could know what was wrong with it.

@Pretzl65

Pretzl65 commented Aug 1, 2022

Copy link
Copy Markdown

Can we start making a more updated version of this? I say we, but I don't really know what I'm doing. I used this tutorial to try and make a music bot, but it didn't work. I'm not sure if that's because the libraries aren't set up right, or because I'm feeding it .mp3 files. But it no workie, and I can't find any other tutorials. I did what the tutorial said and renamed one of the .dll files, and placed both inside my bin/debug folder (Strange that you don't want to reference it, unless FFmpeg does on its own. I'm not sure), and it didn't do anything. I think I would have felt better if it threw an error so I could know what was wrong with it.

Same goes for me... the only thing I was able to find out is that it seems to get stuck at Line 59 ("await ffmpeg.StandardOutput.BaseStream.CopyToAsync(stream);") ... no idea why or how to fix it though! :/

@Sombody101

Copy link
Copy Markdown

Same goes for me... the only thing I was able to find out is that it seems to get stuck at Line 59 ("await ffmpeg.StandardOutput.BaseStream.CopyToAsync(stream);") ... no idea why or how to fix it though! :/

I got it working at some point, but I then switched to LavaLink. It requires you to have Java installed and to have a second terminal open to run it, but works great. It automatically searches for the song. You don't even need to install .mp3 files (you can if you want to still, just might not work with LavaLink). It would also be a good idea to switch over to DSharpPlus (if you decide to use LavaLink) because they have that linked with their API. So you don't have to do much to get it connected with the terminal that hosts LavaLink.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment