1const recorder = require('node-record-lpcm16');
2
3// Imports the Google Cloud client library
4const speech = require('@google-cloud/speech');
5
6// Creates a client
7const client = new speech.SpeechClient();
8
9/**
10 * TODO(developer): Uncomment the following lines before running the sample.
11 */
12// const encoding = 'Encoding of the audio file, e.g. LINEAR16';
13// const sampleRateHertz = 16000;
14// const languageCode = 'BCP-47 language code, e.g. en-US';
15
16const request = {
17 config: {
18 encoding: encoding,
19 sampleRateHertz: sampleRateHertz,
20 languageCode: languageCode,
21 },
22 interimResults: false, // If you want interim results, set this to true
23};
24
25// Create a recognize stream
26const recognizeStream = client
27 .streamingRecognize(request)
28 .on('error', console.error)
29 .on('data', data =>
30 process.stdout.write(
31 data.results[0] && data.results[0].alternatives[0]
32 ? `Transcription: ${data.results[0].alternatives[0].transcript}\n`
33 : '\n\nReached transcription time limit, press Ctrl+C\n'
34 )
35 );
36
37// Start recording and send the microphone input to the Speech API.
38// Ensure SoX is installed, see https://www.npmjs.com/package/node-record-lpcm16#dependencies
39recorder
40 .record({
41 sampleRateHertz: sampleRateHertz,
42 threshold: 0,
43 // Other options, see https://www.npmjs.com/package/node-record-lpcm16#options
44 verbose: false,
45 recordProgram: 'rec', // Try also "arecord" or "sox"
46 silence: '10.0',
47 })
48 .stream()
49 .on('error', console.error)
50 .pipe(recognizeStream);
51
52console.log('Listening, press Ctrl+C to stop.');