我正在尝试使用ytdl和discord.js下载并播放从youtube获取的音频文件:

        ytdl(url)
            .pipe(fs.createWriteStream('./music/downloads/music.mp3'));

        var voiceChannel = message.member.voiceChannel;
        voiceChannel.join().then(connection => {
            console.log("joined channel");
            const dispatcher = connection.playFile('./music/downloads/music.mp3');
            dispatcher.on("end", end => {
                console.log("left channel");
                voiceChannel.leave();
            });
        }).catch(err => console.log(err));
        isReady = true


我成功地播放了./music/downloads/中的mp3文件,没有ytdl部分(ytdl(url).pipe(fs.createWriteStream('./music/downloads/music.mp3'));)。但是,当代码中包含该部分时,该机器人便会加入并离开。

这是带有ytdl部分的输出:

Bot has started, with 107 users, in 43 channels of 3 guilds.
joined channel
left channel


这是不包含ytdl部分的输出:

Bot has started, with 107 users, in 43 channels of 3 guilds.
joined channel
[plays mp3 file]
left channel


为什么会这样,我该如何解决?

最佳答案

需要播放音频流时,请使用playStream而不是playFile。

const streamOptions = { seek: 0, volume: 1 };
var voiceChannel = message.member.voiceChannel;
        voiceChannel.join().then(connection => {
            console.log("joined channel");
            const stream = ytdl('https://www.youtube.com/watch?v=gOMhN-hfMtY', { filter : 'audioonly' });
            const dispatcher = connection.playStream(stream, streamOptions);
            dispatcher.on("end", end => {
                console.log("left channel");
                voiceChannel.leave();
            });
        }).catch(err => console.log(err));

关于javascript - 使用discord.js和ytdl-core播放音频文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47045805/

10-13 04:14