问题描述
我正在尝试使用 BinaryJS 将音频从包含音频文件的服务器流式传输到客户端.我的代码的灵感来自这个问题中的代码:Playing来自 Node.js 上的 Web Audio API 的 PCM 流
I'm trying to stream audio from a server containing an audio file to a client using BinaryJS. My code was inspired by the code in this question: Playing PCM stream from Web Audio API on Node.js
这是我的服务器代码的样子:
Here's what my server code looks like:
// create a BinaryServer using BinaryJS
var BinaryServer = require('binaryjs').BinaryServer;
// gotta be able to access the filesystem
var fs = require('fs');
// create our server listening on a specific port
var server = BinaryServer({port: 8080});
// do this when a client makes a request
server.on('connection', function(client){
// get the audio file
var file = fs.createReadStream(__dirname + '/JDillaLife.mp3');
// convert to int16
var len = file.length;
var buf = new Int16Array(len);
while(len--){
buf[len] = data[len]*0xFFFF;
}
var Stream = client.send();
Stream.write(buf.buffer);
console.log("Server contacted and file sent");
});
console.log('Server running on port 8080');
还有我的客户端代码:
var Speaker = require('speaker');
var speaker = new Speaker({
channels: 2,
bitDepth: 32,
sampleRate: 44100,
signed: true
});
var BinaryClient = require('binaryjs').BinaryClient;
var client = BinaryClient('http://localhost:8080');
client.on('stream', function(stream, meta){
stream.on('data', function(data){
speaker.write(data);
});
});
这是一个非常粗略的草稿,我几乎可以肯定它不会立即发挥出色,但是现在当我运行时它会抛出一个错误,这似乎与 var buf = new Int16Array 这一行有关(len);
,我不确定为什么会这样.它说存在类型错误",但我不确定为什么在将新对象分配给空变量时会发生这种情况.我是 JS 的新手(以及整个无类型语言的一般事物)所以这是我分配的内容的问题吗?
This is a very rough draft and I'm almost certain it won't play nicely right away, but right now it's throwing an error when I run that seems to take issue with the line var buf = new Int16Array(len);
, and I'm not sure why this is happening. It says there's a "type error," but I'm not sure why this would happen when assigning a new object to an empty variable. I'm new to JS (and the whole untyped languages thing in general) so is this an issue with what I'm assigning?
推荐答案
我认为这里的问题是您正在访问 file.length,而 file 是一个我认为没有 length 属性的 Stream 对象.所以你所做的基本上是在说
I think the issue here is that you're accessing file.length, while file is a Stream object which I don't think have a length property. So what you're doing is basically saying
new Int16Array(undefined);
因此类型错误.
fs.createReadStream 记录在这里;https://nodejs.org/api/fs.html#fs_fs_createreadstream_path_options
fs.createReadStream is documented here; https://nodejs.org/api/fs.html#fs_fs_createreadstream_path_options
您可以使用 Stream 对象使用 stream.read(256) 以块的形式读取数据,如此处所述;https://nodejs.org/api/stream.html#stream_readable_read_size
You can use the Stream object to read data in chunks using stream.read(256), as documented here; https://nodejs.org/api/stream.html#stream_readable_read_size
希望这能给你足够的指导来继续!
Hopefully that gives you enough pointers to proceed!
这篇关于从服务器到客户端的 Web 音频流文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!