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.
- Have FFMPEG installed & the environment path set for it in Windows [link]
- Have Microsoft Visual Studio (VS) installed [link]
- Have Node.js installed.[link]
- 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:
- Add the Discord.js dependency to the project;
var Discord = require('discord.js');
- 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;
- Next make the function to intercept the correct message;
bot.on('message', message =>{ENTER CODE HERE});
- Create an if statement to check if the message is correct & if the bot is ready;
if (isReady && message.content === 'MESSAGE'){ENTER CODE HERE}
- Set the bot to unready so that it cannot process events until it finishes;
isReady = false;
- Create a variable for the channel that the message-sender is currently in;
var voiceChannel = message.member.voice.channel;
- Join that channel and keep track of all errors;
voiceChannel.join().then(connection =>{ENTER CODE HERE}).catch(err => console.log(err));
- Create a refrence to and play the audio file;
const dispatcher = connection.play('./audiofile.mp3');
- Slot to wait until the audio file is done playing;
dispatcher.on("end", end => {ENTER CODE HERE});
- Leave channel after audio is done playing;
voiceChannel.leave();
- 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 theStreamDispatcher
ended right away.
To debug this, take a look at the
error
event ofStreamDispatcher
.
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
Json Object Array Inside Array Find and Replace in JavaScript
How to Force Update Child Component from Parent Component in Reactjs
Delete Row on Remove Click React
How to Remove Errors Warnings from Console
Converting Byte Array to String in JavaScript
Filter Array of Dates Between Two Dates
Force Download an Image from Src Using JavaScript
How to Remove Forward and Backward Slashes from String in JavaScript
How to Know If Two Arrays Have the Same Values
Re-Render Same Component on Url Change in React
How to Get First N Number of Elements from an Array
How to Replace Double/Multiple Slash to Single in Url
Blocking Device Rotation on Mobile Web Pages
How to Access Session Variables and Set Them in JavaScript
Way to Access Const from Another Component in React
Determine If String Is in Base64 Using JavaScript