| 167 | } |
| 168 | |
| 169 | async function detectAudioIntent( |
| 170 | projectId, |
| 171 | sessionId, |
| 172 | filename, |
| 173 | encoding, |
| 174 | sampleRateHertz, |
| 175 | languageCode |
| 176 | ) { |
| 177 | // [START dialogflow_detect_intent_audio] |
| 178 | const fs = require('fs'); |
| 179 | const util = require('util'); |
| 180 | const {struct} = require('pb-util'); |
| 181 | // Imports the Dialogflow library |
| 182 | const dialogflow = require('@google-cloud/dialogflow'); |
| 183 | |
| 184 | // Instantiates a session client |
| 185 | const sessionClient = new dialogflow.SessionsClient(); |
| 186 | |
| 187 | // The path to identify the agent that owns the created intent. |
| 188 | const sessionPath = sessionClient.projectAgentSessionPath( |
| 189 | projectId, |
| 190 | sessionId |
| 191 | ); |
| 192 | |
| 193 | // Read the content of the audio file and send it as part of the request. |
| 194 | const readFile = util.promisify(fs.readFile); |
| 195 | const inputAudio = await readFile(filename); |
| 196 | const request = { |
| 197 | session: sessionPath, |
| 198 | queryInput: { |
| 199 | audioConfig: { |
| 200 | audioEncoding: encoding, |
| 201 | sampleRateHertz: sampleRateHertz, |
| 202 | languageCode: languageCode, |
| 203 | }, |
| 204 | }, |
| 205 | inputAudio: inputAudio, |
| 206 | }; |
| 207 | |
| 208 | // Recognizes the speech in the audio and detects its intent. |
| 209 | const [response] = await sessionClient.detectIntent(request); |
| 210 | |
| 211 | console.log('Detected intent:'); |
| 212 | const result = response.queryResult; |
| 213 | // Instantiates a context client |
| 214 | const contextClient = new dialogflow.ContextsClient(); |
| 215 | |
| 216 | console.log(` Query: ${result.queryText}`); |
| 217 | console.log(` Response: ${result.fulfillmentText}`); |
| 218 | if (result.intent) { |
| 219 | console.log(` Intent: ${result.intent.displayName}`); |
| 220 | } else { |
| 221 | console.log(' No intent matched.'); |
| 222 | } |
| 223 | const parameters = JSON.stringify(struct.decode(result.parameters)); |
| 224 | console.log(` Parameters: ${parameters}`); |
| 225 | if (result.outputContexts && result.outputContexts.length) { |
| 226 | console.log(' Output contexts:'); |