I am currently experiencing difficulties with playing audio through a discord bot that I created. The bot is designed to download a song from YouTube using ytdl-core and then play it, but for some reason, the song stops after a few seconds of playing.
Below is my "play.ts" file which contains the play command: (sorry for the messy code, I'm still trying to figure things out.)
import { CommandInteraction, SlashCommandBuilder } from "discord.js";
import { getVoiceConnection, createAudioPlayer, createAudioResource, NoSubscriberBehavior } from '@discordjs/voice';
import { join } from "path";
import ytdl from 'ytdl-core';
import fs from 'fs';
export const data = new SlashCommandBuilder()
.addStringOption(option =>
option.setName("link")
.setDescription("Link to the audio source to be played.")
.setRequired(true)
)
.setName("play")
.setDescription("Plays audio from given URL.");
export async function execute(interaction: CommandInteraction) {
if (!interaction.guildId) {
return interaction.reply("Oops! Something went wrong.");
}
const url = interaction.options.getString("link");
const connection = getVoiceConnection(interaction.guildId);
if (!connection) {
return interaction.reply("The bot is not in a voice channel. Please join one before using this command.");
}
const audioplayer = createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Pause,
},
});
const download = ytdl(url, { filter: 'audioonly' });
const writestream = fs.createWriteStream('audio.mp4');
const pathtoresource = join('audio.mp4');
download.pipe(writestream);
const resource = createAudioResource(pathtoresource, {
inlineVolume: true,
metadata: {
title: "SONG",
},
});
audioplayer.play(resource);
connection.subscribe(audioplayer);
return interaction.reply(`Playing from: ${url}`);
}
The issue seems to be that sometimes the audio doesn't play at all or only plays for a few seconds. It could be due to the download not completing on time for playback, but I'm unsure how to make it wait for the ytdl download.
Any assistance would be greatly appreciated! (once again, sorry for the messy code, I'm still learning)
EDIT: These are the intents:
const client = new Client({
intents: ["Guilds", "GuildMessages", "DirectMessages", "GuildVoiceStates"],
});