我正在尝试使用Binaryjs和一个简单的HTML客户端构建音频流服务器,这是我的节点服务器设置:
var BinaryServer = require('binaryjs').BinaryServer;
var fs = require('fs');
// Start Binary.js server
var server = BinaryServer({port: 9000}); //,chunkSize:150000
// Wait for new user connections
server.on('connection', function(client){
var file = fs.createReadStream(__dirname + '/testsong.mp3');
client.send(file);
var chunks = [];
file.on('data', function(data){
console.log(client._socket._socket._writableState.finished);
if (chunks.length < 40) {
chunks.push(data);
} else {
if (client._socket._socket._writableState.finished === false) {
console.log("Send");
client.send(Buffer.concat(chunks));
}
chunks = [];
}
});
});
它加载40个块然后将它们发送回连接的用户。这是我的index.html
<html>
<script src="binaryjs.js"></script>
<script src="jquery.js"></script>
<head>
</head>
<body>
<script>
var client = new BinaryClient('ws://localhost:9000');
window.AudioContext = window.AudioContext || window.webkitAudioContext;
var context = new AudioContext();
var delayTime = 0;
var init = 0;
var audioStack = [];
var nextTime = 0;
client.on('stream', function(stream, meta){
stream.on('data', function(data) {
context.decodeAudioData(data, function(buffer) {
audioStack.push(buffer);
//Not sure if this line works.
// if ((init!=0) || (audioStack.length > 10)) { // make sure we put at least 10 chunks in the buffer before starting
init++;
scheduleBuffers();
// }
},
function(err) {
console.log("err(decodeAudioData): "+err);
});
});
});
function scheduleBuffers() {
while ( audioStack.length) {
var buffer = audioStack.shift();
var source = context.createBufferSource();
source.buffer = buffer;
source.connect(context.destination);
if (nextTime == 0) {
nextTime = context.currentTime + 0.05; /// add 50ms latency to work well across systems - tune this if you like
}
source.start(nextTime);
nextTime+=source.buffer.duration; // Make the next buffer wait the length of the last buffer before being played
};
}
</script>
</body>
</html>
代码部分有效,歌曲开始播放,但不断停止,模糊。我认为问题在于,有些块会提前播放,有些则会播放到很晚。已经过测试,在发送之前更改了延迟并更改了chunkSize,chunkLength以及许多其他代码。
我还读过Web Audio API有几个错误,或者我不知道如何实现它,context.decodeAudioData()总是会为一首歌引发相同数量的null
错误。
有没有办法调整它以使其正常播放或我该怎么办?解码似乎部分工作,所以可能有更好的延迟(已经尝试改变它)。