我已经能够成功地将实时音频从我的麦克风流式传输到我的节点服务器。我现在想将其流式传输到所有连接的客户端。我一直在尝试使用网络套接字来做到这一点。
我正在使用此命令流式传输音频
ffmpeg -f alsa -i hw:0 -acodec mp2 -f mp3 -r 30 http://localhost:8086
节点获取缓冲区数组,我将它写入所有连接的客户端,就像使用“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);
}
};
知道如何在浏览器上播放这些数据吗?我尝试关注此主题,但 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);
});
}