I am try to create a small nodejs server that will take requests that will stream audio. I'm currently using 0.10.5 api. I must admit I am a newbie to nodejs. I'm not sure how to edit this code to successfully stream audio.
var http = environment.http;
//Steaming Audio
var path = environment.path,
util = environment.util,
url = environment.url;
http.createServer(function (request, response) {
var queryData = url.parse(request.url, true).query;
window.console.log(queryData);
if (!queryData.hasOwnProperty('file')) {
response.writeHead(404, {
'Content-Type': 'text/plain'
});
response.end();
window.console.log('In here');
} else {
window.console.log('In here2');
var filePath = queryData.file;
var extension = self.getExtension(filePath);
var acceptedExtensions = ['mp3', 'wav', 'aiff'];
if ($.inArray(extension, acceptedExtensions) == -1) {
response.writeHead(404, {
'Content-Type': 'text/plain'
});
response.end();
}
var stat = environment.fs.statSync(filePath);
response.writeHead(200, {
'Content-Type': 'audio/mpeg',
'Content-Length': stat.size
});
//window.console.log(filePath);
var readStream = environment.fs.createReadStream(filePath);
//var readable = new require('stream').Readable();
readStream.pipe(response);
}
}).listen(10000);
When I make a request
http://localhost:10000/?file=/Users/acasanova/Music/Cass%20Beats/45th.mp3
The console shows "In here2" and then "In here". I'm trying to figure out why it seems to fulfill the request twice and why the audio isn't being streamed.
One very simple reason why you are getting the first response 'in here' is probably because your browser is looking for a favicon file, which your node application responds with a 404. This is what I have generally observed when you try to write a simple app in node.js.
As to why the audio isn't streaming, I have to look into it properly. But I don't know why you are trying to set a content-length as node.js httpServer, as it supports writing chunked responses (Transfer-Encoding: chunked) by default (which is what you need for streaming). There is something obviously wrong with this approach, but I will have to look into it properly to give you a definate answer.