How would I correctly receive/send raw audio data?
I currently receive raw audio data over WebSockets (with Node.js) and write them to a file. Data is sent as byte[]
array of 1024 byte in size from a Java client. Audio format is PCM, Mono, 16bit, 44100Hz.
I'm trying to pass on the raw audio data directly to browser, but it doesn't seem to work. What am I missing? Sorry for being new at this. The browsers I tested all support (Webkit) AudioContext. For each package received in browser, I get the following message:
Uncaught SyntaxError: An invalid or illegal string was specified. audio.php:19 1024
Node.js (server):
var WebSocketServer = require('ws').Server
, wss = new WebSocketServer({port: 8081});
var Clients = [];
function findClient(url) {
return (Clients.indexOf(url));
}
wss.on('connection', function(ws) {
Clients.push(ws);
console.log('Connected: %s', ws.upgradeReq.url);
console.log('Clients: %s', Clients.length);
ws.on('message', function(message, flags) {
if(flags.binary) {
ws.send(message, {binary:true});
}
console.log('data arrived: %s', message);
});
ws.on('close', function(user) {
console.log('Disconnected: %s', ws.upgradeReq.url);
Clients.splice(findClient(ws));
console.log('Clients: %s', Clients.length);
});
Client browser:
<script language="javascript">
if (window.webkitAudioContext) {
var ctx = new webkitAudioContext();
} else if (window.AudioContext) {
var ctx = new AudioContext();
}
function testSound(buff) {
var src = ctx.createBufferSource();
src.buffer = ctx.createBuffer(buff, false);
//src.looping = false;
src.connect(ctx.destination);
src.noteOn(0);
}
var ws = new WebSocket('ws://localhost:8081');
ws.binaryType = 'arraybuffer';
ws.onmessage = function(e) {
console.log(e.data.byteLength);
testSound(e.data);
}
</script>