Created
March 27, 2014 20:08
-
-
Save riston/9817292 to your computer and use it in GitHub Desktop.
Broken websocket mp3 stream implementation
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
<!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> |
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 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 | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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