Reputation: 469
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');
And my client code:
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);
});
});
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?
Upvotes: 2
Views: 2096
Reputation: 2641
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);
and hence the type error.
fs.createReadStream is documented here; https://nodejs.org/api/fs.html#fs_fs_createreadstream_path_options
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!
Upvotes: 1