How to Play Audio File into Channel

How to Play Audio File Into Channel?

GitHub Project: LINK

In order to do this there are a few things you have to make sure of first.

  1. Have FFMPEG installed & the environment path set for it in Windows [link]
  2. Have Microsoft Visual Studio (VS) installed [link]
  3. Have Node.js installed.[link]
  4. Have Discord.js installed in VS.

From there the steps are quite simple. After making your project index.js you will start typing some code. Here are the steps:

  1. Add the Discord.js dependency to the project;

var Discord = require('discord.js');


  1. Create out client variable called bot;

var bot = new Discord.Client();
3. Create a Boolean variable to make sure that the system doesn't overload of requests;

var isReady = true;


  1. Next make the function to intercept the correct message;

bot.on('message', message =>{ENTER CODE HERE});


  1. Create an if statement to check if the message is correct & if the bot is ready;

if (isReady && message.content === 'MESSAGE'){ENTER CODE HERE}


  1. Set the bot to unready so that it cannot process events until it finishes;

isReady = false;


  1. Create a variable for the channel that the message-sender is currently in;

var voiceChannel = message.member.voice.channel;


  1. Join that channel and keep track of all errors;

voiceChannel.join().then(connection =>{ENTER CODE HERE}).catch(err => console.log(err));


  1. Create a refrence to and play the audio file;

const dispatcher = connection.play('./audiofile.mp3');


  1. Slot to wait until the audio file is done playing;

dispatcher.on("end", end => {ENTER CODE HERE});


  1. Leave channel after audio is done playing;

voiceChannel.leave();


  1. Login to the application;

bot.login('CLIENT TOKEN HERE');

After you are all finished with this, make sure to check for any un-closed brackets or parentheses. i made this because it took my hours until I finally found a good solution so I just wanted to share it with anybody who is out there looking for something like this.

Play audio file from a commands in Discord.js

You'll need to find a voice channel first, for example the one the user typing the command is in (if any) like this :

const voiceChannel = message.member.voice.channel;
if (!voiceChannel) return message.channel.send("No voice channel.");

Then join the channel and then play your file :

voiceChannel.join()
.then(connection => {
connection.play('/path/to/yourFile.mp3');
});

You can check what else you can do by reading the docs.

Problems playing audio files in Discord

Past the 3rd day I resolved to find other library I could use to solve the problem, turns out I found a solution using FS!

Instead of only try to play the file, I've created a stream and then I just play the stream... In terms of performance that's not the greatest solution ever, but it works!

That's how it goes:

   const {createReadStream } = require('fs')
const { join } = require('path');
const { joinVoiceChannel, createAudioPlayer, createAudioResource,
getVoiceConnection, entersState, StreamType, AudioPlayerStatus,
VoiceConnectionStatus, AudioResource } = require("@discordjs/voice");

module.exports = {
name: 'laugh',
aliases: ["l"],

run: async(client, message, args) => {
const player = createAudioPlayer();
const connection = joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator,
selfDeaf: false,
}).subscribe(player);

let resource = createAudioResource(createReadStream(join(__dirname, 'som/laugh.mp3')), {
inlineVolume : true
});
resource.volume.setVolume(0.9);
console.log(join(__dirname, 'som/laugh.mp3'));

player.play(resource)
player.on(AudioPlayerStatus.AutoPaused, () => {
player.stop();

});

Something I must alert is about Replit not resolving properly Node.js 17 and other dependencies, so to bring your Bot up 24/7 use Heroku and GitHub. To finish the GUILD_VOICE_STATES Intents are required to be set, I was using 32767 but somehow this wasn't working.

That's it!

Discord.js bot trying to play mp3 file on voice channel - no error and also no sound

For discord.js voice to work, you need to have following packages installed (as stated in the docs under the installation section): either @discordjs/opus or opusscript.

npm install @discordjs/opus

Also discord.js depends on prism-media and you should have ffmpeg installed for this to work properly.

npm install ffmpeg-static

If you don't want to install ffmpeg as a npm package and you already have ffmpeg installed, make sure to add it to the PATH environmental variable and restart your working environment.

The OP said, that restarting his computer after adding ffmpeg to the PATH worked.

Rest of the info from comments:

Also your message "Playing ok!" is wrong, it means that the bot is not speaking... See above you have if (!speaking) { ... }. So when you get this message after the bot joined the voice channel, something is wrong, because the StreamDispatcher ended right away.

To debug this, take a look at the error event of StreamDispatcher.

Play local music files using djs v13

There are 2 problems here.

Firstly, the path is completely wrong. It is not a string and even if you try to change it to a string it will be invalid as the first argument ends with audio.mp3, and the second one is audio.mp3. Use this path instead:

let resource = createAudioResource(join('..', 'music', 'audio.mp3')); 

Secondly, you are playing audio in the player, but not the voice connection. You must subscribe to the audio player.

This should be the final code:

const player = createAudioPlayer()
joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
}).subscribe(player)
message.guild.me.voice.setRequestToSpeak(true);
let resource = createAudioResource(join('..', 'music', 'audio.mp3'));

player.play(resource)

How to play specific audio file in voice channel?

Since discord.js v12, GuildMember.voiceChannel was changed to GuildMember.voice.channel

var voiceChannel = msg.member.voice.channel


Related Topics



Leave a reply



Submit