You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

50 lines
1.1 KiB
JavaScript

const WebSocket = require('ws');
const fs = require('fs');
const pcm_file = './16bit-8000.raw';
7 years ago
let interval = 0,
sampleRate = 8000,
bytePerSample = 2,
7 years ago
channels = 2,
bytesChunk = (sampleRate * bytePerSample * channels),
7 years ago
offset = 0,
pcmData,
wss;
7 years ago
fs.readFile(pcm_file, (err, data) => {
if (err) throw err;
pcmData = data;
openSocket();
});
function openSocket() {
wss = new WebSocket.Server({ port: 8080 });
console.log('Server ready...');
wss.on('connection', function connection(ws) {
console.log('Socket connected. sending data...');
if (interval) {
clearInterval(interval);
}
interval = setInterval(function() {
7 years ago
sendData();
}, 500);
});
}
7 years ago
function sendData() {
let payload;
if (offset >= pcmData.length) {
clearInterval(interval);
7 years ago
offset = 0;
return;
}
7 years ago
payload = pcmData.subarray(offset, (offset + bytesChunk));
offset += bytesChunk;
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
7 years ago
client.send(payload);
}
});
}