I am using discord.js v13 and attempting to play audio files using #discordjs/voice. My problem is that the bot will do everything correctly, but when the green circle that indicates that a sound is coming from the bot appears, I don't hear anything. I don't think this is an audio issue with my headphones because I can hear everything else fine, including other people on discord.
Here is my code:
const { getVoiceConnection, joinVoiceChannel, AudioPlayerStatus, createAudioResource, getNextResource, createAudioPlayer, NoSubscriberBehavior } = require('#discordjs/voice');
module.exports = {
name: "play",
category: "music",
description: "plays audio",
usage: "<id | mention>",
run: async (client, message, args) => {
const voiceChannel = message.member.voice.channel;
const connection = joinVoiceChannel({
channelId: voiceChannel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
});
const audioPlayer = createAudioPlayer();
connection.subscribe(audioPlayer);
audioPlayer.play(createAudioResource('./sound/audio.mp3'));
}
}
Any help is appreciated.
Simply writing createAudioResource('./sound/audio.mp3') isn't the correct syntax to get the audio resource of the mp3 file you have, the only thing you miss is the createReadStream() which will create a readable stream before transforming it into an audio resource. In clear, just change
audioPlayer.play(createAudioResource('./sound/audio.mp3'));
to
audioPlayer.play(createAudioResource(createReadStream('./sound/audio.mp3')));
If this still doesn't solve your answer maybe try adding options like the inlineVolume option as the second parameter:
audioPlayer.play(createAudioResource(createReadStream('./sound/audio.mp3')),
{ inlineVolume: true });
Related
So I'm working on a Discord bot using JS and DiscordJSv14, and want the bot to use audio from a voice chat to send to another bot, some type of listen and snitch bot.
So far I got the Bot's connecting to the voice call but can't get any of the packets to send to the other bot.
Here's some code I've got so far:
const connection = joinVoiceChannel({
channelId: C.id,
guildId: guild.id,
adapterCreator: guild.voiceAdapterCreator,
selfDeaf: false,
selfMute: false,
group: this.client.user.id,
});
if (isListener) {
console.log("Listener Is Joining Voice And Listening...");
const encoder = new OpusEncoder(48000, 2);
let subscription = connection.receiver.subscribe(ID); // ID = Bot's ID
// Basically client.user.id
subscription.on("data", (chunk) => {
console.log(encoder.decode(chunk));
});
}
Console won't log anything about the chunk
Using DiscordJSv14 + #discordjs/opus
Everything worked fine I just needed to add the following code below.
this.client = new Client({
intents: [GatewayIntentBits.GuildVoiceStates, GatewayIntentBits.GuildMessages, GatewayIntentBits.Guilds],
});
The audio player doesn't play anything in the voice channel. There is only the green ring around the profile but no sound. Does anyone know why? I'm using discord.js v13
const { Client, Intents, discord } = require('discord.js');
const client = new Client({ intents: [ Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_VOICE_STATES ]});
const { joinVoiceChannel } = require('#discordjs/voice');
const { createAudioPlayer, AudioPlayerStatus, createAudioResource } = require('#discordjs/voice');
client.on("message", message => {
if(message.content.startsWith("!play")){
const channel = message.member.voice.channel
const player = createAudioPlayer();
player.on(AudioPlayerStatus.Playing, () => {
message.channel.send("Now playing")
})
player.on("error", error => {
console.log(error)
})
const resource = createAudioResource('./music.mp3');
player.play(resource)
const connection = joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
});
const subscription = connection.subscribe(player)
if(subscription){
setTimeout(() => {
subscription.unsubscribe()
}, 15_000)
}
}
})
Your code seems to be fine whats causing the problem is that you need to install ffmpeg-static ( you can find the relating post from the discord.js documentation here ). ffmpeg is used for converting mp3 files to something your discord bot can play. You should also have #discordjs/voice and discord.js but by the looks of it you have.
Please let me know if installing ffmpeg-static solves your problem
So, It's been two long days traying to figure what the reck is going on... I'm creating a Bot to my Discord Channel that plays an audio.mp3 when a command is written, like !laugh then the bot should enter the voice channel and reproduce laugh.mp3. I've tried in so manny different ways but the bot keeps entering the channel, the green circle quickly appears but no sound is played...
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
}).subscribe(player)
let resource = createAudioResource(join('./som/', 'laugh.mp3'));
player.play(resource)
player.on(AudioPlayerStatus.AutoPaused, () => {
player.stop();
});
}
}
I've already tried to caugh error but apparently nothing is wrong, I already have all intents in my index.js.
So, anyone could help me find a solution?
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!
I try to detect in real-time whether each member is speaking or not on a voice channel using discord.js v13.
In other words, I want to reproduce the green circle of discord in my application.
However, I couldn't find a suitable code example or article.
Could you give me some advice?
Edit:
Based on the advice, I was able to solve it.
The example of Recorder BOT was useful.
A code example is shown below.
const { Client, Intents, VoiceChannel } = require('discord.js')
const { joinVoiceChannel, getVoiceConnection, entersState, VoiceConnectionStatus } = require('#discordjs/voice');
const client = new Client({ intents: ['GUILD_VOICE_STATES', 'GUILD_MESSAGES', 'GUILDS'] });
client.on("messageCreate", async (message) => {
if(message.content.toLowerCase() === "test") {
var connection = getVoiceConnection(message.guildId)
if(!connection){
connection = joinVoiceChannel({
channelId: message.member.voice.channelId,
guildId: message.guildId,
adapterCreator: message.guild.voiceAdapterCreator,
selfDeaf: false,
selfMute: true,
});
}
try {
await entersState(connection, VoiceConnectionStatus.Ready, 20e3);
connection.receiver.speaking.on("start", (userId) => {
console.log( `${userId} start` );
});
connection.receiver.speaking.on("end", (userId) => {
console.log( `${userId} end` );
});
console.log( "Ready" );
} catch (error) {
console.warn(error);
}
}
});
client.login('YOUR-TOKEN')
Searching for this seems to suggest this used to be possible but was famously broken, because the event wouldn't fire, or would fire only once.
The client.voiceStateUpdate event used to give you a VoiceState that had a speaking property, which would tell you if someone was speaking (which seems like it never really worked).
The current discord.js documentation for VoiceState shows this property no longer exists, and you cannot do what you're asking using discord.js alone.
Edit: as per MrMythical's comment below, discord.js/voice has voiceRecievers, which exposes voiceReciever.speakingMap.users, a map of users currently speaking. you may get events for it by registering a listener.
I recently installed Discord.js 13.1.0 and my music commands broke because, apparently, channel.join(); is not a function, although I have been using it for months on 12.5.3...
Does anybody know a fix for this?
Some parts of my join command:
const { channel } = message.member.voice;
const voiceChannel = message.member.voice.channel;
await channel.join();
It results in the error.
Discord.js no longer supports voice. You need to use the other package they made (#discordjs/voice). You can import joinVoiceChannel from there.
//discord.js and client declaration
const { joinVoiceChannel } = require('#discordjs/voice');
client.on('messageCreate', message => {
if(message.content === '!join') {
joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
})
}
})