Skip to content

Instantly share code, notes, and snippets.

@crertel
Created July 2, 2019 20:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crertel/bb41ac3e12b9c352517cefff46eea2c6 to your computer and use it in GitHub Desktop.
Save crertel/bb41ac3e12b9c352517cefff46eea2c6 to your computer and use it in GitHub Desktop.
Gross streaming server hack
var http = require("http");
var express = require('express');
var fs = require("fs");
var app = express();
var files = [
[fs.readFileSync("./music/1.mp3"), 128 * 1024],
[fs.readFileSync("./music/2.mp3"), 64 * 1024],
];
var currClients = [];
var updateRate = 2000;
var currPlayHead = 0;
var currPlayFile = 0;
function stream() {
// get next chunk
var [currFileBytes, currFileBitrate] = files[currPlayFile];
var chunk = currFileBytes.slice(currFileBitrate*currPlayHead, currFileBitrate*(currPlayHead+1));
if (chunk.length > 0) {
// for each subscribed client
currClients = currClients.filter( (client) => !client.socket.destroyed);
currClients.forEach( function( client) {
client.write( chunk, "binary" );
});
currPlayHead++;
console.log(`Streaming Chunk ${currPlayHead} to ${currClients.length}`);
} else {
console.log("changing track");
currPlayHead = 0;
currPlayFile++;
currPlayFile = ( currPlayFile >= files.length) ? 0 : currPlayFile ;
}
// schedule ourselves again
setTimeout( stream, updateRate);
}
function setupStream() {
setTimeout(stream, 0);
}
app.get("/stream", function(req,res) {
//res.status(200);
res.writeHead(200, {
"Content-Type": "audio/mpeg"
});
currClients.push(res);
});
app.get("/", function(req,res) {
res
.status(200)
.send(`<html>
<head>
</head>
<body>
<audio src="./stream" type="audio/mpeg"></audio>
</body>
</html>
`);
});
setupStream();
var server = http.createServer(app);
server.listen(3000);
@courajs
Copy link

courajs commented Jul 2, 2019

Great little hack!!!
If you want, line 36: currPlayFile = ( currPlayFile >= files.length) ? 0 : currPlayFile ;
can be simplified to: currPlayFile = currPlayFile % files.length;

@crertel
Copy link
Author

crertel commented Jul 3, 2019

@courajs excellent point, had forgotten that trick--used to do it in ringbuffer implementations all the time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment