Created
July 2, 2019 20:54
-
-
Save crertel/bb41ac3e12b9c352517cefff46eea2c6 to your computer and use it in GitHub Desktop.
Gross streaming server hack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 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
Great little hack!!!
If you want, line 36:
currPlayFile = ( currPlayFile >= files.length) ? 0 : currPlayFile ;
can be simplified to:
currPlayFile = currPlayFile % files.length;