node.js - 我有来自 ffmpeg 的音频数据流,如何在浏览器中播放它?

标签 node.js audio ffmpeg client-side

我已经能够成功地将实时音频从我的麦克风传输到我的 Node 服务器。我现在想将其流式传输给所有连接的客户端。我一直在尝试使用网络套接字来做到这一点。

我正在使用此命令流式传输音频

ffmpeg -f alsa -i hw:0 -acodec mp2 -f mp3 -r 30 http://localhost:8086

Node 获取缓冲区数组,然后我将其写入所有连接的客户端,就像使用“ws”包一样

// HTTP Server to accept incomming MP3 Stream (audio)
var audioServer = require('http').createServer( function(request, response) {

       audioSocket.broadcast(data, {binary:true});

}).listen(8086);

var audioSocket = new (require('ws').Server)({port: 8088});
audioSocket.broadcast = function(data, opts) {

    for( var i in this.clients ) {
        this.clients[i].send(data);
    }
};

知道如何在浏览器上播放这些数据吗?我尝试遵循此topic但decodeAudioData()方法失败。

我的客户端代码

node={};
var audio = new WebSocket('ws://localhost:8088/');
audio.binaryType = "arraybuffer";
var context = new webkitAudioContext();

audio.onmessage = function(data){
    node.buf=data.data;
    node.sync=0;
    node.retry=0;
    decode(node);
}

function syncStream(node){ // should be done by api itself. and hopefully will.
    var buf8 = new Uint8Array(node.buf); 
    buf8.indexOf = Array.prototype.indexOf;
    var i=node.sync, b=buf8;
    while(1) {
        node.retry++;
        i=b.indexOf(0xFF,i); if(i==-1 || (b[i+1] & 0xE0 == 0xE0 )) break;
        i++;
    }
    if(i!=-1) {
        var tmp=node.buf.slice(i); //carefull there it returns copy
        delete(node.buf); node.buf=null;
        node.buf=tmp;
        node.sync=i;
        return true;
    }
    return false;
}

function decode(node) {
    context.decodeAudioData(node.buf,
    function(decoded){
        node.source  = context.createBufferSource();
        node.source.connect(context.destination);
        node.source.buffer=decoded; 
        node.source.noteOn(context.currentTime);
        console.log('IT WORKED!  DECODED', decoded);
    },
    function(){ // only on error attempt to sync on frame boundary
        //console.log('error');
        if(syncStream(node)) decode(node);
    });
}

最佳答案

您这样做是为了好玩还是为了现实生活中的产品?我们已经在我们的一个项目中成功使用了 vlc 流媒体服务器,在 Ubuntu 上安装它很容易 http://www.videolan.org/vlc/streaming.html

关于node.js - 我有来自 ffmpeg 的音频数据流,如何在浏览器中播放它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19871798/

相关文章:

node.js - 在使用 Nightmare JS 的 AWS 上,导出为 PDF 可以使用一个端口,但不能使用另一个端口

c++ - opencv rtsp流协议(protocol)

ffmpeg 转换原始视频双倍大小的视频,第二部分没有音频

http - ffmpeg - 如何传递 http header ?

Node.Js npm PDFKit 在调用 doc.end() 时崩溃

node.js - Yarn - Node Sass 还不支持我当前的环境

node.js - 第一条消息后机器人响应太慢

android - libgdx音频播放

java - Wav 文件作为频率图像

javascript - 来自缓存的 HTML 音频元素源