Discord.js audio player doesn't play audio - javascript

I have been trying to create an audioPlayer with the Discord.js library. I created a /join command that joins my bot to the voice channel and then plays a local audio file.
const { SlashCommandBuilder, ChannelType } = require('discord.js');
const { joinVoiceChannel, createAudioPlayer, createAudioResource, AudioPlayerStatus } = require('#discordjs/voice')
const path = require('node:path');
const player = createAudioPlayer();
module.exports = {
data: new SlashCommandBuilder().setName('join').setDescription('Join to a voice channel').addChannelOption((option) =>
option.setName('channel').
setDescription('The channel to join').
setRequired(true).
addChannelTypes(ChannelType.GuildVoice)
),
async execute(interaction) {
const voiceChannel = interaction.options.getChannel('channel');
try {
const voiceConnection = joinVoiceChannel({
channelId: voiceChannel.id,
guildId: interaction.guild.id,
adapterCreator: interaction.guild.voiceAdapterCreator,
})
player.on(AudioPlayerStatus.Playing, () => {
console.log('The audio player has started playing!');
});
player.on('error', error => {
console.error(`Error: ${error.message} with resource ${error.resource.metadata.title}`);
});
let resource = createAudioResource('"C:\\Users\\gerso\\Documents\\CS-P\\discord-bot\\audio\\track.mp3"', { inlineVolume: true })
player.play(resource)
const subscription = voiceConnection.subscribe(player)
if(subscription) {
setTimeout(() => subscription.unsubscribe(), 15_000)
}
} catch (error) {
console.error(error)
}
await interaction.reply('player')
},
};
When I use the command on discord the bot joins the voice channel but it doesn't play any audio and the console doesn't show any error.
Note: I have already installed ffmpeg-static in my project.

Related

Discord audio playing issue

Explanation
I have this code that plays youtube video audio in voice channels.
When it joins the channel I get an error that says "ffmpeg not found". I ran the terminal command "npm i ffmpeg-static" and it worked fine but after a couple of minutes I get a long error and the music stops playing.
This is my code:
client.on("ready", async () => {
for (const channelId of Channels) {
joinChannel(channelId);
await new Promise(res => setTimeout(()=>res(2), 500))
}
function joinChannel(channelId) {
client.channels.fetch(channelId).then(channel => {
const VoiceConnection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator
});
const resource = createAudioResource(ytdl("https://youtu.be/0J2gdL87fVs", {
filter: "audioonly"
}), {
inlineVolume: true
});
resource.volume.setVolume(0.2);
const player = createAudioPlayer()
VoiceConnection.subscribe(player);
player.play(resource);
player.on("idle", () => {
try {
player.stop()
}catch (e) {}
try {
VoiceConnection.destory()
}catch (e) {}
joinChannel(channelId)
})
}).catch(console.error)
}
})

Can you stream Audio from a URL in a discord.js resource

How do I play audio from a url with discord.js v13.
I used this code and it didn't work.
const connection = joinVoiceChannel({
channelId: channel_id.id,
guildId: guild_id,
adapterCreator: message.guild.voiceAdapterCreator,
});
const player = createAudioPlayer();
const resource = createAudioResource('http://radioplayer.kissfmuk.com/live/')
player.play(resource)
connection.subscribe(player)
I have activated all Intents, the bot shows a green circle but no audio is playing.
Do you have an Idea how it works?
A link of which you are trying to make a resource of, has to return an audio file.
Live audio broadcasts will not work with your current code.
If the url gives you E.g. an .mp3 file, the code should work.
Example Function:
const Discord = require('discord.js');
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_VOICE_STATES] });
const config = require('./config/config.json');
const { joinVoiceChannel, createAudioPlayer, NoSubscriberBehavior, createAudioResource, AudioPlayerStatus, VoiceConnectionStatus, entersState } = require('#discordjs/voice');
const { join } = require('path');
client.once('ready', () => {
console.log(config.onlineMessage);
const channels = client.guilds.cache.find(f => f.name==="<Server Name>").channels;
JoinChannel(channels.cache.find(r => r.name === "<Channel Name>"), './background.mp3', 0.025);
});
client.login(config.token);
function JoinChannel(channel, track, volume) {
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guildId,
adapterCreator: channel.guild.voiceAdapterCreator,
});
const player = createAudioPlayer();
resource = createAudioResource(join(__dirname, track), { inlineVolume: true });
resource.volume.setVolume(volume);
connection.subscribe(player);
connection.on(VoiceConnectionStatus.Ready, () => {console.log("ready"); player.play(resource);})
connection.on(VoiceConnectionStatus.Disconnected, async (oldState, newState) => {
try {
console.log("Disconnected.")
await Promise.race([
entersState(connection, VoiceConnectionStatus.Signalling, 5_000),
entersState(connection, VoiceConnectionStatus.Connecting, 5_000),
]);
} catch (error) {
connection.destroy();
}
});
player.on('error', error => {
console.error(`Error: ${error.message} with resource ${error.resource.metadata.title}`);
player.play(getNextResource());
});
player.on(AudioPlayerStatus.Playing, () => {
console.log('The audio player has started playing!');
});
player.on('idle', () => {
connection.destroy();
})
}
The answer was pretty simple, I just need to subscribe to the connection before I play the resource!
const connection = joinVoiceChannel({
channelId: channel_id.id,
guildId: guild_id,
adapterCreator: message.guild.voiceAdapterCreator,
});
const resource =
createAudioResource('https://streams.ilovemusic.de/iloveradio8.mp3', {
inlineVolume: true
})
const player = createAudioPlayer();
connection.subscribe(player)
player.play(resource)

DiscordJS music bot disconnects immediately after starting to play the song

I try to play a Youtube URL but when it starts playing it stops after 1 second. mp3 files are working fine, it just doesn't work when I try to play Youtube URLs.
Here is my Code:
case 'play':
{
const Channel = ['903334978199388271'];
for (const channelId of Channel) {
joinChannel(channelId);
}
function joinChannel(channelId) {
Client.channels
.fetch(channelId)
.then((channel) => {
const VoiceConnection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
const player = createAudioPlayer();
VoiceConnection.subscribe(player);
player.play(
createAudioResource(
ytdl('https://www.youtube.com/watch?v=sPPsOmQh76A'),
),
);
})
.catch(console.error);
}
}
break;
I had the same problem before, the problem is ytdl-core, so you can use ytdl-core-discord instead. Here is an example:
const { Client, Intents, MessageEmbed } = require('discord.js')
const ytdl = require('ytdl-core-discord')
const {
joinVoiceChannel,
createAudioPlayer,
createAudioResource,
StreamType
} = require('#discordjs/voice')
const client = new Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MEMBERS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_VOICE_STATES /// <= Don't miss this :)
]
});
var prefix = '!'
client.on('ready', async () => {
console.log('Client is Ready...');
});
client.on('messageCreate', async (message) => {
if (message.content.trim().toLocaleLowerCase() === prefix + 'play') {
const channel = client.channels.cache.get('Channel ID Here')
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guildId,
adapterCreator: channel.guild.voiceAdapterCreator
});
const player = createAudioPlayer();
const resource = createAudioResource(await ytdl('https://www.youtube.com/watch?v=sPPsOmQh76A'), { inputType: StreamType.Opus });
player.play(resource);
connection.subscribe(player);
}
});
client.login('Bot Token Here!');

voiceChannel.join() isn't a function node v16 discord.js

I made a bot that plays music. I upgraded to NodeJS v16.6.1 and voiceChannel.join doesn't work anymore.
I already tried using const { voiceChannel } = require('#discord.js/voice'); but it just says module not found.
Code:
const ytdl = require("ytdl-core");
const ytSearch = require("yt-search");
module.exports = {
name: 'play',
description: 'Joins and plays a video from youtube',
async execute(message, args) {
const voiceChannel = message.member.voice.channel;
if (!voiceChannel) return message.channel.send('You need to be in a channel to execute this command');
const permissions = voiceChannel.permissionsFor(message.client.user);
if (!permissions.has('CONNECT')) return message.channel.send('You dont have the neccesary permissions');
if (!permissions.has("SPEAK")) return message.channel.send('You dont have the neccesary permissions');
if (!args.length) return message.channel.send('Define Video');
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(`Now Playing **${video.title}**`)
} else {
message.channel.send('No videos found');
}
}
}```
As the error says, voiceChannel#join is not, in fact, a function. While it did exist on Discord.js v12, which I assume you were using before updating your Node.js version, note that it is nowhere to be found in the Discord.js v13 documentation on VoiceChannel. Instead, you are to migrate to #discordjs/voice, whose joinVoiceChannel function can be used as a replacement.

Discord js doesn't plays audio anymore

I had a base discordjs code that could play 2 audio files, leave and join voice channels, but I did created a new file with this code followed from a youtube video:
const ytSearch = require('yt-search');
module.exports = {
name: 'play',
descreption: 'Play',
async execute(message, args) {
const voiceChannel = message.member.voice.channel;
if (!voiceChannel) return message.send('PALI! Egy voice channelben bent kéne lenne, már nemazé!');
const permissions = voiceChannel.permissionsFor(message.client.user);
if (!permissions.has('Player')) return message.reply('Kéne rang is nem gondolnád?, hogy a bánat egyeki a lelked!');
if (!args.length) return message.channel.reply('KÖZÖLDNÉDHOGYMIAKUKITAKARSZ?? (Need more argumets)');
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: 100 })
on('finish', () => {
voiceChannel.leave();
});
await message.reply(`Most játszom: ***${video.title}$***`)
}
else {
message.channel.send('Nem találtam videót.')
}
}
}
Then I tried to imploment it into my other js file, but after I did it it gave me errors so I gave it up and deleted all that stuff, but now the original code just doesn't wants to play audio, it doesn't gives me errors or anything, I tried everthing I could but I couldn't solve it. Any solutions?
Here's the code:
const Discord = require('discord.js');
const client = new Discord.Client();
//const ytdl = require('ytdl-core');
//const ytSearch = require('yt-search');
var prefix = ';';
client.login('CENSORED');
client.on('ready', () =>{
console.log('\n ----------WELCOME TO ADY STUDIOS AUTOMATIC------------')
})
client.on('message', async message => {
if (message.content === ';join') {
if (message.member.voice.channel) {
const connection = await message.member.voice.channel.join();
} else {
message.reply('You need to join a voice channel first!');
}
}
if(message.content === ';leave'){
message.guild.me.voice.channel.leave();
}
if (message.content === ';coconut') {
const connection = await message.member.voice.channel.join();
const dispatcher = connection.play('./coconut.m4a');
}
if (message.content === ';roll'){
const connection = await message.member.voice.channel.join();
const dispatcher = connection.play('./rickroll.m4a');
}
});
{ "dependencies": { "#discordjs/opus": "^0.3.2", "discord.js": "^12.3.1", "ffmpeg-static": "^4.2.7", "mysql": "^2.18.1", "opusscript": "0.0.7", "request": "^2.88.2", "ytdl-core": "^4.2.1" } } install disc should be work

Categories

Resources