マイクからノード サーバーにライブ オーディオを正常にストリーミングできました。これを、接続されているすべてのクライアントにストリーミングしたいと思います。私はWebソケットでそれをやろうとしています。
このコマンドでオーディオをストリーミングしています
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);
});
}