【问题标题】:How do I play sound in my node.js chatroom?如何在我的 node.js 聊天室中播放声音?
【发布时间】:2021-06-07 17:32:00
【问题描述】:

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

【问题讨论】:

标签: javascript node.js express socket.io


【解决方案1】:

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

【讨论】:

  • 当有人将扬声器连接到该服务器并一遍又一遍地听到 1000 次 ping 声的某天复活节彩蛋 ?
  • 哈哈,是的@Trevor
  • 我的问题是 ping 功能在 index.js 中,所以我必须添加到 index.js
  • 使用 node.js 时不允许使用新音频
  • 这就是我制作项目前 20 行的方式。
【解决方案2】:

这是可能的,但有点棘手。您可以使用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']);

【讨论】:

  • 表示找不到所有玩家。
  • 然后安装播放器?
【解决方案3】:

这不是答案,这只是 ping 代码所在位置的代码 sn-p。

  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();”发出声音。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多