NodeJS discord.js v13 bot加入语音频道但不播放任何内容

5n0oy7gb  于 2023-04-20  发布在  Node.js
关注(0)|答案(1)|浏览(139)

我想编码的音乐hadler应该能够播放音乐和声音的mp3。

以下是我的计划:

musicPlayer.background("mp3 url", voicechannel)这应该在后台播放一个mp3文件。如果播放完毕,它应该重新开始。如果再次调用此函数,它应该删除旧的mp3并播放新的。音量:0.5
musicPlayer.playSound("mp3", voicechannel)此函数不应删除背景音乐并在背景音乐上播放另一个mp3。这不应循环。音量:1.0
musicPlayer.stop(voicechannel)这将停止音乐和声音并离开语音通道。

我的编码:

const { createAudioPlayer, createAudioResource, joinVoiceChannel, AudioPlayerStatus } = require('@discordjs/voice');

const audioPlayers = new Map();

async function playBackgroundMusic(url, voiceChannel) {
    const connection = joinVoiceChannel({
      channelId: voiceChannel.id,
      guildId: voiceChannel.guild.id,
      adapterCreator: voiceChannel.guild.voiceAdapterCreator,
      volume: 0.5, // Set the volume here
    });
  
    const player = createAudioPlayer();
  
    const resource = createAudioResource(url, {
      inlineVolume: true,
    });
  
    player.play(resource);
  
    connection.subscribe(player);
  
    audioPlayers.set(voiceChannel.guild.id, player);
  
    connection.on('stateChange', (_, newState) => {
      if (newState.status === VoiceConnectionStatus.Disconnected) {
        audioPlayers.delete(voiceChannel.guild.id);
      }
    });
  
    player.on(AudioPlayerStatus.Idle, () => {
      player.play();
    });
  
    connection.on('debug', console.debug);
    connection.on('error', console.error);
  }
  
  async function playSoundEffect(url, voiceChannel) {
    const connection = joinVoiceChannel({
      channelId: voiceChannel.id,
      guildId: voiceChannel.guild.id,
      adapterCreator: voiceChannel.guild.voiceAdapterCreator,
      volume: 1.0, // Set the volume here
    });
  
    const player = createAudioPlayer();
  
    const resource = createAudioResource(url, {
      inlineVolume: true,
    });
  
    player.play(resource);
  
    connection.subscribe(player);
  
    player.on(AudioPlayerStatus.Idle, () => {
      connection.destroy();
    });
  
    connection.on('debug', console.debug);
    connection.on('error', console.error);
  }

  async function stopAudio(voiceChannel) {
    const player = audioPlayers.get(voiceChannel.guild.id);
  
    if (player) {
      player.stop();
      const connection = player.state.subscription.connection;
      connection.destroy();
      audioPlayers.delete(voiceChannel.guild.id);
    }
  }

module.exports = {
  background: playBackgroundMusic,
  playSound: playSoundEffect,
  stop: stopAudio,
};

感谢您的帮助!

我试着使用不同的mp3文件。它加入了语音频道,但不播放任何东西。

ttcibm8c

ttcibm8c1#

我忘了加上这个意图:

Intents.FLAGS.GUILD_VOICE_STATES

我的错

相关问题