通过网络套接字播放音频

时间:2018-06-29 11:53:39

标签: node.js websocket

我正在建立聊天,我希望用户收到声音通知(如果有新消息)。目前,我正在发送客户端将收到的所有文件,如下所示:

var http_files = {};
 [
    ["/jquery.min.js","application/javascript"],
    ["/css/main.css","text/css"],
    ["/resumesound.mp3","audio/mpeg"], <-- doesn't work
    ["/css/normalize.css","text/css"],
    ["/js/main.js","text/javascript"],
    ["/js/vendor/modernizr-2.6.2.min.js","text/javascript"],
    ["/chat-frontend.js","application/javascript"],
    ["/index.html","text/html"]
 ].forEach(function(fn){
     http_files[fn[0]]={
         content : fs.readFileSync('.'+fn[0]).toString(),
         contentType : fn[1]
     };
 });
var server = http.createServer(function(request, response) {
     // this doubles as a way to serve the files, and a connection for websocket to use
     var file = http_files[request.url];
     if (file) {
         response.writeHeader(200,{"content-type" : file.contentType});
         response.write(file.content);
         return response.end();
     }
     response.writeHeader(404,{"content-type" : "text/plain"});
     response.write("not found");
     return response.end();

 });

但是由于某些原因,音频无法播放,并且在尝试播放音频时会在控制台中显示该音频。

  

DOMException:由于找不到受支持的源而无法加载。

实现:

var sound = '/resumesound.mp3';
var audio = new Audio(sound);
audio.play();

1 个答案:

答案 0 :(得分:1)

由于音频是二进制而非纯文本,因此在将文件发送给客户端之前,我必须“取消字符串化”。

更改此行即可达到目的:

content : fs.readFileSync('.'+fn[0]).toString(),

收件人:

content : fs.readFileSync('.'+fn[0]),

代码:

var http_files = {};
 [
    ["/jquery.min.js","application/javascript"],
    ["/css/main.css","text/css"],
    ["/resumesound.mp3","audio/mpeg"],
    ["/css/normalize.css","text/css"],
    ["/js/main.js","text/javascript"],
    ["/js/vendor/modernizr-2.6.2.min.js","text/javascript"],
    ["/chat-frontend.js","application/javascript"],
    ["/index.html","text/html"]
 ].forEach(function(fn){
     http_files[fn[0]]={
         content : fs.readFileSync('.'+fn[0]).toString(),
         contentType : fn[1]
     };
 });