-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathserver.js
95 lines (77 loc) · 2.14 KB
/
server.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
'use strict'
require('dotenv').load()
const express = require('express');
const bodyParser = require('body-parser')
const app = express();
const expressWs = require('express-ws')(app);
const Nexmo = require('nexmo');
const { Readable } = require('stream');
const speech = require('@google-cloud/speech');
// this is used with the heroku one-click install.
// if you are running locally, use GOOGLE_APPLICATION_CREDENTIALS to point to the file location
let config = null;
if (process.env.GOOGLE_APPLICATION_CREDENTIALS === undefined) {
config = {
projectId: 'nexmo-extend',
credentials: {
client_email: process.env.GOOGLE_CLIENT_EMAIL,
private_key: process.env.GOOGLE_PRIVATE_KEY.replace(/\\n/g, '\n')
}
}
}
const client = new speech.SpeechClient(config||null);
const nexmo = new Nexmo({
apiKey: "dummy",
apiSecret: "dummy",
applicationId: process.env.APP_ID,
privateKey: process.env.PRIVATE_KEY || './private.key'
});
app.use(bodyParser.json());
app.get('/ncco', (req, res) => {
let nccoResponse = [
{
"action": "connect",
"endpoint": [{
"type": "websocket",
"content-type": "audio/l16;rate=16000",
"uri": `ws://${req.hostname}/socket`
}]
}
];
res.status(200).json(nccoResponse);
});
app.post('/event', (req, res) => {
console.log('EVENT LOG::', req.body)
res.status(204).end();
});
// Nexmo Websocket Handler
app.ws('/socket', (ws, req) => {
let request ={
config: {
encoding: 'LINEAR16',
sampleRateHertz: 16000,
languageCode: process.env.LANG_CODE || 'en-US'
},
interimResults: false
};
const recognizeStream = client
.streamingRecognize(request)
.on('error', console.error)
.on('data', data => {
console.log(
`Transcription: ${data.results[0].alternatives[0].transcript}`
);
});
ws.on('message', (msg) => {
if (typeof msg === "string") {
let config = JSON.parse(msg);
} else {
recognizeStream.write(msg);
}
});
ws.on('close', () => {
recognizeStream.destroy();
})
});
const port = process.env.PORT || 8000;
app.listen(port, () => console.log(`Example app listening on port ${port}!`))