如何在我的 node.js 聊天室中播放声音?

时间:2021-03-09 19:25:21

标签: javascript node.js express socket.io

我一整天都在寻找如何用 node.js 播放声音,我不能使用“document.getElementById”,也不能使用“new Audio”。我希望它能够在我在聊天室中执行 @everyone 时播放声音。音频文件名为“ping.mp3”,与我的主 node.js 文件位于同一路径中。我需要一些建议或代码片段。谢谢!

3 个答案:

答案 0 :(得分:-1)

这是可能的,但有点棘手。您可以使用 play-sound 为您处理:

var player = require('play-sound')(opts = {})
 
player.play('foo.mp3', function(err){
  if (err) throw err
});

它的主要作用是在环境中寻找声音播放器并尝试使用其中之一播放 mp3:

const { spawn, execSync } = require('child_process');
// List of players used
const players = [
    'mplayer',
    'afplay',
    'mpg123',
    'mpg321',
    'play',
    'omxplayer',
    'aplay',
    'cmdmp3'
];
// find a player by seeing what command doesn't error
let player;
for(const p of players) {
  if (isExec(p)) {
    player = p;
    break;
  }
}

function isExec(command) {
  try{
    execSync(command)
    return true
  }
  catch {
    return false
  }
}
spawn(player, ['ping.mp3']);

答案 1 :(得分:-2)

如果您正在创建 node.js 服务器,node.js 是后端/服务器端,因此如果在那里“播放”声音,用户将无法听到任何发生的事情。因此,您必须使用“new Audio()”在客户端执行此操作,当客户端收到包含“@everyone”的消息时(我不明白您为什么不能使用,您可以发送 mp3 文件 {{3 }})。 我还在 to the client with the page. 上为你做了一个例子。

答案 2 :(得分:-2)

这不是答案,这只是 ping 代码所在位置的代码片段。

  function highlight(message){
    if(message == "") {
        return message
    }
    let mentions = message.match(/@\b([A-Za-z0-9]+)\b/g)
    let urlCheck1 = message.split(` `)
    
    if (mentions === null ) { return message }
    for (i = 0; i < mentions.length; i++) {
      let urlCheck = urlCheck1[i].includes(`http`)
        let mention = mentions[i].substring(1)
        if(sesskx.has(mention) && !urlCheck) {
            message = message.replace(mentions[i], `<span class="name-color">@${mention}</span>`)
        } else if (mention == 'everyone') {
            ping.play();
            message = message.replace(mentions[i], `<span class="name-color">@${mention}</span>`)
        } else if (mention == 'here') {
            ping.play();
            message = message.replace(mentions[i], `<span class="name-color">@${mention}</span>`)
        }
        else {
          return message;
        }
    }
    return message
 };

我想要“ping.play();”发出声音。

相关问题