| 112 | } |
| 113 | |
| 114 | async function syncRecognizeWords( |
| 115 | filename, |
| 116 | encoding, |
| 117 | sampleRateHertz, |
| 118 | languageCode |
| 119 | ) { |
| 120 | // [START speech_sync_recognize_words] |
| 121 | // Imports the Google Cloud client library |
| 122 | const fs = require('fs'); |
| 123 | const speech = require('@google-cloud/speech'); |
| 124 | |
| 125 | // Creates a client |
| 126 | const client = new speech.SpeechClient(); |
| 127 | |
| 128 | /** |
| 129 | * TODO(developer): Uncomment the following lines before running the sample. |
| 130 | */ |
| 131 | // const filename = 'Local path to audio file, e.g. /path/to/audio.raw'; |
| 132 | // const encoding = 'Encoding of the audio file, e.g. LINEAR16'; |
| 133 | // const sampleRateHertz = 16000; |
| 134 | // const languageCode = 'BCP-47 language code, e.g. en-US'; |
| 135 | |
| 136 | const config = { |
| 137 | enableWordTimeOffsets: true, |
| 138 | encoding: encoding, |
| 139 | sampleRateHertz: sampleRateHertz, |
| 140 | languageCode: languageCode, |
| 141 | }; |
| 142 | const audio = { |
| 143 | content: fs.readFileSync(filename).toString('base64'), |
| 144 | }; |
| 145 | |
| 146 | const request = { |
| 147 | config: config, |
| 148 | audio: audio, |
| 149 | }; |
| 150 | |
| 151 | // Detects speech in the audio file |
| 152 | const [response] = await client.recognize(request); |
| 153 | response.results.forEach(result => { |
| 154 | console.log('Transcription: ', result.alternatives[0].transcript); |
| 155 | result.alternatives[0].words.forEach(wordInfo => { |
| 156 | // NOTE: If you have a time offset exceeding 2^32 seconds, use the |
| 157 | // wordInfo.{x}Time.seconds.high to calculate seconds. |
| 158 | const startSecs = |
| 159 | `${wordInfo.startTime.seconds}` + |
| 160 | '.' + |
| 161 | wordInfo.startTime.nanos / 100000000; |
| 162 | const endSecs = |
| 163 | `${wordInfo.endTime.seconds}` + |
| 164 | '.' + |
| 165 | wordInfo.endTime.nanos / 100000000; |
| 166 | console.log(`Word: ${wordInfo.word}`); |
| 167 | console.log(`\t ${startSecs} secs - ${endSecs} secs`); |
| 168 | }); |
| 169 | }); |
| 170 | // [END speech_sync_recognize_words] |
| 171 | } |