Audio player doesn't play the mp3 discord.js - javascript

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

Related

Discord bot not giving reply [duplicate]

This question already has an answer here:
message.content doesn't have any value in Discord.js
(1 answer)
Closed last month.
Can someone help me out? I'm actually stuck. This the the source code for a bot I made to send GIFs when requesed by a user in a server. The bot is online and connecting to the Discord API.
Discord bot getting online image
The bot should be activated when typed !gif , in keyword the user can type any categorie or emotion they want and the bot would get the gif.
There are no errors shown yet but the bot is still not replying.
No reply image
Bot online image
I am also getting valid reply when used the giphy api url.
const Discord = require('discord.js');
require('dotenv').config();
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on("messageCreate", async (message) => {
const tokens = message.content.split(" ");
if (tokens[0] == "!gif") {
const keywords = tokens.slice(1, tokens.length).join(" ");
const url = `http://api.giphy.com/v1/gifs/search?q=tag&api_key=token&limit=5`;
const response = await fetch(url);
const result = await response.json();
const index = Math.floor(Math.random() * result.results.length);
message.channel.send(result.results[index].url);
}
});
client.login(process.env.DISCORD_BOT_TOKEN);
I tried many online fixes none worked I also tried changing version of Discord.js, node-fetch as well as dotenv but none worked.
Discord.js v14
const { Client, GatewayIntentBits, Events } = require('discord.js')
require('dotenv').config()
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildMessages,
],
})
client.on(Events.MessageCreate, async (message) => {
if (message.author.id === client.user.id) return
const token = message.content.split(' ')
if (token[0] === '!gif')
message.channel.send({
content: `<#${message.author.id}>`,
files: ['https://media.tenor.com/fTTVgygGDh8AAAAM/kitty-cat-sandwich.gif'],
})
})
client.on(Events.ShardReady, () => {
console.log(`Logged in as ${client.user.tag}!`)
})
client.login(process.env.TOKEN)

Problems playing audio files in Discord

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!

discord.js bot playing audio but no sound?

I was planning to add some voice features to my discord bot, but for some reason when I run my code, it doesn't make sound while discord does show the green circle around my bot, showing that it's making sound. It also does't log any errors or anything else, does anyone know what's wrong with my code?
Code:
if (command == "soundtest") {
mongo().then(async (mongoose) => {
const { voice } = msg.member
if (voice.channelID) {
const vc = voice.channel
// console.log(channel)
try {
vc.join().then(connection => {
connection.play(path.join(__dirname, 'Bastille_Pompeii.mp3'))
})
} catch(e) {
console.log("error")
console.log(e)
}
} else {
msg.channel.send(`You must join a voice channel to use this command`)
}
})
}
Thanks for reading!
This code should work for you:
const { createReadStream } = require('fs');
const { join } = require('path');
const { createAudioResource, StreamType, createAudioPlayer, joinVoiceChannel } = require('#discordjs/voice');
const player = createAudioPlayer()
joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
}).subscribe(player)
let resource = createAudioResource(join('./folder/', '<song_name>.mp3'));
player.play(resource)
As you said, you tried to play file named Bastille_Pompeii.mp3, so you need to define resource like this: let resource = createAudioResource(join('./musicfiles/', 'Bastille_Pompeii.mp3'));

Running into an error with getting music bot to join VC

const ytdl = require('ytdl-core');
const ytSearch = require('yt-search');
module.exports = {
name: 'play',
description: "plays music in voice chat",
async execute(message, args, Discord){
const voiceChannel = message.member.voice.channel;
if (!voiceChannel) return message.channel.send('You need to be in a voice channel to listen to music!');
const permissions = voiceChannel.permissionsFor(message.client.user);
if (!permissions.has('CONNECT')) return message.reply("You don't have the correct permissions to request music!");
if (!permissions.has('SPEAK')) return message.reply("You don't have the correct permissions to request music!");
if (!args.length) return message.channel.send("You Can't Request for no Music Silly >_<");
const connection = await voiceChannel.join();
const videoFinder = async (query) => {
const videoResult = await ytSearch(query);
return (videoResult.videos.length > 1) ? videoResult.videos[0] : null;
}
const video = await videoFinder(args.join(' '));
if(video){
const stream = ytdl(video.url, {filter: 'audioonly'});
connection.play(stream, {seek: 0, volume: 1})
.on('finish', () =>{
voiceChannel.leave();
});
await message.reply(`:Thumbsup: Now Playing >>>${video.title}<<<`)
} else {
message.reply('No Video Results Found :(');
}
}
}
My Error message is const connection = await voiceChannel.join();
TypeError: voiceChannel.join is not a function
If any of you have a suggestion that may work please feel free to edit it. It can also only detect if someone is in voice chat at start up of the bot, so if your in voice chat at start of bot it sends the in voice chat message while your in and out of voice chat
While transitioning from discord.js v12 - v13 we have encountered a breaking change that is switching to #discordjs/voice a seperate library for voice to play with discord.js, now as suggested from the comment here I see you're using the most latest version of discord.js where the VoiceChannel#join method no longer exists. You have to propose the following changes:
Install #discordjs/voice using npm install #discordjs/voice
You need to establish a voiceConnection, and further create an AudioPlayer instance and go ahead and call the AudioPlayer#subscribe method to this player, you would have to do some base additions for the same which are exhibited below:
const {
joinVoiceChannel,
createAudioPlayer,
createAudioResource
} = require('#discordjs/voice');
const connection = joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator,
});
const stream = ytdl(video.url, {
filter: "audioonly"
});
const player = createAudioPlayer();
const resource = createAudioResource(stream);
async function play() {
await player.play(resource);
connection.subscribe(player);
}
They just made it overcomplex for beginners to comprehend so don't worry! If you feel like you're over- exhausting yourselves you can always downgrade to a lower version like so:
npm uninstall discord.js
npm install discord.js#12.5.3
Welcome to stackoverflow 😄

discord.js - "TypeError: voiceChannel.join is not a function" while trying to make a bot join a voice channel [duplicate]

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
})
}
})

Categories