Skip to content

Instantly share code, notes, and snippets.

@glenpike
Created January 8, 2018 18:37
Show Gist options
  • Save glenpike/0b0d7619b73b1b5d937ae5bc09ec19b2 to your computer and use it in GitHub Desktop.
Save glenpike/0b0d7619b73b1b5d937ae5bc09ec19b2 to your computer and use it in GitHub Desktop.
Express route to transcode an audio file.
//FIXME - investigate settings, etc.
function transcode(file) {
var spawn = require('child_process').spawn
var decode = spawn('flac', [
'--decode',
'--stdout',
file
])
var encode = spawn('lame', [
'-V0',
'-',
'-'
])
decode.stdout.pipe(encode.stdin)
return encode
}
library.get('/play/:id', function(req, res, next) {
console.log('stream');
req.collection.findOne({ _id: req.params.id },
function(e, result) {
if(e) {
console.log('error ', e)
return next(e)
}
if(!result) {
res.status(404).send('Sorry! Can\'t find it.');
} else {
console.log('play file ', result);
var fs = require('fs')
stat = fs.statSync(result.path);
res.writeHead(200, {
'Content-Type': 'audio/mpeg',
'Content-Length': stat.size
});
var readStream;
if(-1 === result.mime.indexOf('mpeg')) {
console.log('not an mpeg file, will transcode ', result);
readStream = transcode(result.path).stdout;
} else {
readStream = fs.createReadStream(result.path);
}
readStream.pipe(res);
readStream.on('end', function() {
console.log('readStream end');
});
}
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment