-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
55 lines (46 loc) · 1.47 KB
/
server.js
File metadata and controls
55 lines (46 loc) · 1.47 KB
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
// server.js
const WebSocket = require('ws');
const speech = require('@google-cloud/speech');
const client = new speech.SpeechClient();
const encoding = 'LINEAR16';
const sampleRateHertz = 48000;
const languageCode = 'en-US';
const request = {
config: {
encoding: encoding,
sampleRateHertz: sampleRateHertz,
languageCode: languageCode,
audioChannelCount: 1, // Tell Google it's mono
},
interimResults: true, // For smoother streaming experience
};
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', (ws) => {
console.log('Client connected.');
// Create a recognition stream from Google
const recognizeStream = client
.streamingRecognize(request)
.on('data', (data) => {
const transcript = data.results?.[0]?.alternatives?.[0]?.transcript;
if (transcript) {
// Send the transcript back to the Flutter client
ws.send(JSON.stringify({ transcript }));
}
})
.on('error', (err) => {
console.error('Google Speech error:', err);
})
.on('end', () => {
console.log('Google stream ended.');
});
// When audio data arrives from the client, write it into the recognition stream
ws.on('message', (message) => {
// Here, message is a Buffer containing raw PCM data.
recognizeStream.write(message);
});
ws.on('close', () => {
console.log('Client disconnected.');
recognizeStream.end();
});
});
console.log('WebSocket server listening on ws://localhost:8080');