1

我尝试播放 Youtube URL,但当它开始播放时,它会在 1 秒后停止。mp3 文件工作正常,但当我尝试播放 Youtube URL 时它不起作用。

这是我的代码:

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;
4

1 回答 1

1

我之前也遇到过同样的问题,问题是ytdl-core,所以你可以 ytdl-core-discord改用。这是一个例子:

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!');
于 2021-11-02T12:28:19.677 回答