Skip to content

Instantly share code, notes, and snippets.

@Ravenstine
Created May 23, 2017 17:08
Show Gist options
  • Save Ravenstine/97c164ba63ed9cb773dddf4ae9cb7ad2 to your computer and use it in GitHub Desktop.
Save Ravenstine/97c164ba63ed9cb773dddf4ae9cb7ad2 to your computer and use it in GitHub Desktop.
Rewind Server
'use strict';
const express = require('express');
const fs = require('fs');
const http = require('http');
const https = require('https');
const RewindBuffer = require('./lib/rewind-buffer');
let rewindBuffer = new RewindBuffer({maxFrames: 300});
let app = express();
let httpsServer = https.createServer({
key: fs.readFileSync('./key.pem', 'utf8'),
cert: fs.readFileSync('./cert.pem', 'utf8'),
passphrase: "password"
}, app);
app.get('/stream', function (req, res) {
res.writeHead(200, {'Content-Type': 'audio/mpeg'});
let offset = req.query.offset ? parseInt(req.query.offset) : 0;
let isConnected = true;
rewindBuffer.read(offset, (samples) => {
res.write(Buffer.from(samples), 'binary');
return isConnected;
});
let terminateRead = () => {
console.log('client disconnected');
isConnected = false;
}
req.on("close", terminateRead);
req.on("end", terminateRead);
});
httpsServer.listen(3003);
const options = {
hostname: 'live.scpr.org',
protocol: 'http:',
path: '/kpcclive?ua=SCPRWEB&preskip=true'
};
http.get(options, (res) => {
let secondBuffer = []; // to buffer up 1 second of audio
let frameCount = 0;
let syncWord = '255,251';
let nickelbackTimeout = null;
function bufferAudio (d, x){
let i = 0;
let len = d.length;
while(i<len){
let lastThreeBytes = secondBuffer.slice(secondBuffer.length - 2, secondBuffer.length);
if(lastThreeBytes.toString() === syncWord){
frameCount++;
}
if(frameCount >= 38){
if(x){
debugger
}
rewindBuffer.push(secondBuffer);
secondBuffer = [];
frameCount = 0;
}
secondBuffer.push(d[i]);
i++;
}
}
function playNickelback(){
let d = fs.readFileSync('./resources/nickelbackx.mp3');
console.log('something went wrong');
bufferAudio(d, true);
}
res.on('data', (d) => {
clearTimeout(nickelbackTimeout);
bufferAudio(d);
nickelbackTimeout = setTimeout(playNickelback, 5000);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment