-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
74 lines (62 loc) · 1.95 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
'use strict'
const express = require('express');
const WaveFile = require('wavefile').WaveFile;
const fs = require('fs');
const app = express();
const expressWs = require('express-ws')(app);
const port = 3000;
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
expressWs.getWss().on('connection', function (ws) {
console.log('Websocket connection is open');
});
app.get('/webhooks/answer', (req, res) => {
let nccoResponse = [
{
"action": "talk",
"text": "Please wait while we connect you to the echo server"
},
{
"action": "connect",
"from": "NexmoTest",
"endpoint": [
{
"type": "websocket",
"uri": `wss://${req.hostname}/socket`,
"content-type": "audio/l16;rate=16000",
}
]
}
]
res.status(200).json(nccoResponse);
});
app.post('/webhooks/events', (req, res) => {
console.log(req.body);
res.sendStatus(200);
});
app.ws('/socket', async (ws, req) => {
// Load the sound file
const wav = new WaveFile(fs.readFileSync("./sound.wav"));
/*
Convert file sample rate and bit depth
to the expected values by the Voice API.
*/
wav.toSampleRate(16000);
wav.toBitDepth("16");
/*
1. Get the samples of the audio file (first channel).
2. Break the samples into the size expected by the Voice API
*/
const samples = chunkArray(wav.getSamples()[0], 320);
for (var index = 0; index < samples.length; ++index) {
// Send a buffer over the web socket
ws.send(Uint16Array.from(samples[index]).buffer);
}
});
function chunkArray(array, chunkSize) {
var chunkedArray = [];
for (var i = 0; i < array.length; i += chunkSize)
chunkedArray.push(array.slice(i, i + chunkSize));
return chunkedArray;
}
app.listen(port, () => console.log(`Listening on port ${port}`));