Created
September 8, 2011 18:39
-
-
Save dtrce/1204243 to your computer and use it in GitHub Desktop.
streaming mp3 using nodejs
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'), | |
fileSystem = require('fs'), | |
path = require('path') | |
util = require('util'); | |
http.createServer(function(request, response) { | |
var filePath = 'path_to_file.mp3'; | |
var stat = fileSystem.statSync(filePath); | |
response.writeHead(200, { | |
'Content-Type': 'audio/mpeg', | |
'Content-Length': stat.size | |
}); | |
var readStream = fileSystem.createReadStream(filePath); | |
// We replaced all the event handlers with a simple call to util.pump() | |
util.pump(readStream, response); | |
}) | |
.listen(2000); |
var http = require('http'),
url = require('url'),
fs = require('fs'),
filePath = '/home/risto/Downloads/oleg.mp3',
stat = fs.statSync(filePath);
http.createServer(function(request, response) {
var queryData = url.parse(request.url, true).query;
const skip = typeof(queryData.skip) == 'undefined' ? 0 : queryData.skip;
const startByte = stat.size * skip;
response.writeHead(200, {
'Content-Type': 'audio/mpeg',
'Content-Length': stat.size - startByte
});
// We replaced all the event handlers with a simple call to util.pump()
fs.createReadStream(filePath, {start:startByte}).pipe(response);
})
.listen(2000);
This gives you skipping ^^
Video stream with range.
via: https://medium.com/@daspinola/video-stream-with-node-js-and-html5-320b3191a6b6
var http = require('http'),
url = require('url'),
fs = require('fs'),
filePath = '/home/risto/Downloads/oleg.mp4',
stat = fs.statSync(filePath);
http.createServer(function(request, response) {
const fileSize = stat.size;
const range = request.headers.range;
if (range) {
const parts = range.replace(/bytes=/, "").split("-");
const start = parseInt(parts[0], 10);
const end = parts[1]
? parseInt(parts[1], 10)
: fileSize - 1;
const chunksize = (end - start) + 1;
const readStream = fs.createReadStream(filePath, { start, end });
const head = {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': 'video/mp4',
};
response.writeHead(206, head);
readStream.pipe(response);
} else {
const head = {
'Content-Length': fileSize,
'Content-Type': 'video/mp4',
};
response.writeHead(200, head);
fs.createReadStream(filePath).pipe(response);
}
})
.listen(2000);
^^^ works like charm, thanks!
How to make mp3 stream from folder?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks! super helpful code