Skip to content

Instantly share code, notes, and snippets.

@riston
Created March 27, 2014 20:08
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 riston/9817292 to your computer and use it in GitHub Desktop.
Save riston/9817292 to your computer and use it in GitHub Desktop.
Broken websocket mp3 stream implementation
<!DOCTYPE html>
<html>
<head>
<title>Test websocket</title>
</head>
<script type="text/javascript">
var context = new webkitAudioContext();
var ws = new WebSocket("ws://localhost:8080");
var startTime = context.currentTime;
ws.binaryType = 'arraybuffer';
ws.onmessage = function (evt) {
console.log('Event ', evt);
context.decodeAudioData(
evt.data,
function(buffer) {
playBuffer(buffer);
console.log("Success");
},
function(error) {
console.log("Error");
});
};
ws.onopen = function () {
console.log('Client connection to ws');
};
ws.onclose = function () {
console.log('Connection closed');
};
function playBuffer(buf) {
var source = context.createBufferSource();
source.buffer = buf;
source.connect(context.destination);
source.start(startTime);
startTime = startTime+source.buffer.duration;
}
</script>
<body>
</body>
</html>
var fs = require('fs');
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({
port: 8080,
host: "127.0.0.1"
});
wss.on('connection', function(ws) {
var readStream =
fs.createReadStream("/home/risto/Downloads/oleg.mp3", {
'flags': 'r',
// 'encoding': 'binary',
'mode': 0666,
'bufferSize': 64 * 1024
});
readStream.on('data', function(data) {
ws.send(data, {
binary: true,
mask: false
});
});
});
@riston
Copy link
Author

riston commented Mar 27, 2014

Small comment on #Node chat <\malex> the issue is at the server side. each chunk the server sends should be broken on the frame boundary, then you can play each chunk independently

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