如何获得在语音通道上讲话所花费的时间?

时间:2018-08-24 23:40:04

标签: node.js discord discord.js

我试图确定在语音通道中播放视频的位置。 我正在使用ytdl-core播放视频,但是我不知道ytdl-core是否具有可以做到这一点的功能。我需要以hour:minute:second格式返回的职位。如果我需要另一个库来做就可以了。

这是我用来播放视频的代码:

const commando = require('discord.js-commando');
const ytdl = require('ytdl-core');
var args_res;
var streamOptions;
var servers = {};

function Play(connection, message) {
  var server = servers[message.guild.id];
  server.dispatcher = connection.playStream(ytdl(server.queue[0], {
    filter: "audioonly"
  }), streamOptions);

  server.queue.shift();
  server.dispatcher.on("end", function() {
    if (server.queue[0]) {
      Play(connection, message);
    } else {
      connection.disconnect();
    }
  });
}

class JoinChannelCommand extends commando.Command {
    constructor(client) {
      super(client, {
        name: 'play',
        group: 'audio',
        memberName: 'play',
        description: 'Joins the same voice channel that the person who typed the commands is in, and plays the song.'
      });
    }

    async run(message, args) {
      if (message.member.voiceChannel) {
        if (!message.guild.voiceConnection) {
          if (!servers[message.guild.id]) {
            servers[message.guild.id] = {
              queue: []
            }
          }
          message.member.voiceChannel.join()
            .then(connection => {
              var server = servers[message.guild.id];
              args_res = args.split(" ");
              streamOptions = {
                seek: 0,
                volume: (args_res[1] / 100)
              };

              server.queue.push(args_res[0]);
              console.log(server.queue[0] + "  " + args_res[1]);
              Play(connection, message);
            });
        }
      } else {
        message.reply("You must be in a voice channel for me to join!");
      }
    }

    module.exports = JoinChannelCommand;

谢谢。

1 个答案:

答案 0 :(得分:1)

您可以使用StreamDispatcher.time,因为每次播放新视频时都会重置调度程序。
可以按照您喜欢的时间格式来转换该值:例如,如果您拥有ms = 15600000,则可以通过以下操作获得时间格式:

var ms = 15600000,
  hr = Math.floor(ms / 1000 / 60 / 60),
  mn = Math.floor(ms / 1000 / 60 % 60),
  ss = Math.round(ms / 1000 % 60 % 60);
  
function format(number = 0) {
  return `0${number}`.slice(-2);
}

console.log(`${hr}:${format(mn)}:${format(ss)}`);