简体   繁体   English

如何将音频文件播放到频道中?

[英]How to Play Audio File Into Channel?

How do you play an audio file from a Discord bot?如何从 Discord 机器人播放音频文件? Needs to play a local file, be in JS, and upon a certain message being sent it will join the user who typed the message, and will play the file to that channel.需要播放一个本地文件,在JS中,当某条消息被发送时,它会加入输入消息的用户,并将文件播放到该频道。

GitHub Project: LINK GitHub 项目:链接

In order to do this there are a few things you have to make sure of first.为了做到这一点,您必须首先确保一些事情。

  1. Have FFMPEG installed & the environment path set for it in Windows [ link ]已安装 FFMPEG 并在 Windows [链接] 中为其设置环境路径
  2. Have Microsoft Visual Studio (VS) installed [ link ]安装了 Microsoft Visual Studio (VS) [ 链接]
  3. Have Node.js installed.[ link ]安装了 Node.js。[链接]
  4. Have Discord.js installed in VS.在 VS 中安装 Discord.js。

From there the steps are quite simple.从那里开始的步骤非常简单。 After making your project index.js you will start typing some code.创建项目index.js您将开始键入一些代码。 Here are the steps:以下是步骤:

  1. Add the Discord.js dependency to the project;将 Discord.js 依赖添加到项目中;

var Discord = require('discord.js');

  1. Create out client variable called bot ;创建名为bot 的客户端变量;

var bot = new Discord.Client(); 3. Create a Boolean variable to make sure that the system doesn't overload of requests; 3. 创建一个布尔变量,确保系统不会超载请求;

var isReady = true;

  1. Next make the function to intercept the correct message;接下来制作拦截正确消息的函数;

bot.on('message', message =>{ENTER CODE HERE});

  1. Create an if statement to check if the message is correct & if the bot is ready;创建一个if 语句来检查消息是否正确以及机器人是否准备就绪;

if (isReady && message.content === 'MESSAGE'){ENTER CODE HERE}

  1. Set the bot to unready so that it cannot process events until it finishes;将机器人设置为未就绪状态,使其在完成之前无法处理事件;

isReady = false;

  1. Create a variable for the channel that the message-sender is currently in;为消息发送者当前所在的频道创建一个变量;

var voiceChannel = message.member.voice.channel;

  1. Join that channel and keep track of all errors;加入该频道并跟踪所有错误;

voiceChannel.join().then(connection =>{ENTER CODE HERE}).catch(err => console.log(err));

  1. Create a refrence to and play the audio file;创建引用并播放音频文件;

const dispatcher = connection.play('./audiofile.mp3');

  1. Slot to wait until the audio file is done playing;等待音频文件播放完毕的插槽;

dispatcher.on("end", end => {ENTER CODE HERE});

  1. Leave channel after audio is done playing;音频播放完毕离开频道;

voiceChannel.leave();

  1. Login to the application;登录应用程序;

bot.login('CLIENT TOKEN HERE');

After you are all finished with this, make sure to check for any un-closed brackets or parentheses.完成此操作后,请确保检查任何未关闭的括号或圆括号。 i made this because it took my hours until I finally found a good solution so I just wanted to share it with anybody who is out there looking for something like this.我之所以这样做是因为我花了好几个小时才终于找到了一个好的解决方案,所以我只是想与任何在那里寻找类似问题的人分享它。

不需要膨胀的 Visual Studio .. 方式矫枉过正.. 你只需要 node.js 和通过 npm 的依赖项。

thanks so much!非常感谢!

One thing I will say to help anyone else, is things like where it says ENTER CODE HERE on step 10, you put the code from step 11 IE:为了帮助其他人,我要说的一件事是,在第 10 步中显示在此处输入代码的地方,您将第 11 步中的代码放入 IE:

dispatcher.on("end", end => voiceChannel.leave());

As a complete example, this is how I have used it in my message command IF block:作为一个完整的例子,这是我在我的消息命令 IF 块中使用它的方式:

if (command === "COMMAND") {
        var VC = message.member.voiceChannel;
        if (!VC)
            return message.reply("MESSAGE IF NOT IN A VOICE CHANNEL")
    VC.join()
        .then(connection => {
            const dispatcher = connection.playFile('c:/PAtH/TO/MP3/FILE.MP3');
            dispatcher.on("end", end => {VC.leave()});
        })
        .catch(console.error);
};

I went ahead an included Nicholas Johnson's Github bot code here, but I made slight modifications.我在这里继续使用包含 Nicholas Johnson 的Github 机器人代码,但我做了一些小修改。

  1. He appears to be creating a lock;他似乎在制造一把锁; so I created a LockableClient that extends the Discord Client .所以我创建了一个LockableClient来扩展 Discord Client
  2. Never include an authorization token in the code切勿在代码中包含授权令牌

auth.json授权文件

{
  "token" : "your-token-here"
}

lockable-client.js可锁定的client.js

const { Client } = require('discord.js')

/**
 * A lockable client that can interact with the Discord API.
 * @extends {Client}
 */
class LockableClient extends Client {
  constructor(options) {
    super(options)
    this.locked = false
  }
  lock() {
    this.setLocked(true)
  }
  unlock() {
    this.setLocked(false)
  }
  setLocked(locked) {
    return this.locked = locked
  }
  isLocked {
    return this.locked
  }
}

module.exports = LockableClient;

index.js索引.js

const auth = require('./auth.json')
const { LockableClient } = require('./lockable-client.js')

const bot = new LockableClient()

bot.on('message', message => {
  if (!bot.isLocked() && message.content === 'Gotcha Bitch') {
    bot.lock()
    var voiceChannel = message.member.voiceChannel
    voiceChannel.join().then(connection => {
      const dispatcher = connection.playFile('./assets/audio/gab.mp3')
      dispatcher.on('end', end => voiceChannel.leave());
    }).catch(err => console.log(err))
    bot.unlock()
  }
})

bot.login(auth.token)

This is an semi old thread but I'm going to add code here that will hopefully help someone out and save them time.这是一个半旧的线程,但我将在这里添加代码,希望能帮助某人并节省他们的时间。 It took me way too long to figure this out but dispatcher.on('end') didn't work for me.我花了很长时间才弄清楚这一点,但dispatcher.on('end')对我不起作用。 I think in later versions of discord.js they changed it from end to finish我想在discord.js的后续版本,他们改变它从endfinish

var voiceChannel = msg.member.voice.channel;
    voiceChannel.join()
        .then(connection => {
            const dispatcher = connection.play(fileName);
            dispatcher.on("finish", end => {
                voiceChannel.leave();
                deleteFile(fileName);
            });
        })
        .catch(console.error);

Note that fileName is a string path for example: fileName = "/example.mp3".请注意,fileName 是一个字符串路径,例如:fileName = "/example.mp3"。 Hopefully that helps someone out there :)希望这可以帮助那里的人:)

Update: If you want to detect if the Audio has stopped, you must subscribe to the speaking event.更新:如果您想检测音频是否已停止,您必须订阅speaking事件。

voiceChannel
    .join()
    .then((connection) => {
        const dispatcher = connection.play("./audio_files/file.mp3");

        dispatcher.on("speaking", (speaking) => {
            if (!speaking) {
                voiceChannel.leave();
            }
        });
    })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM