Forked from phsultan/testApiKeyAndGoogleAuthLibrary.js
Created
April 12, 2018 14:05
-
-
Save E3V3A/3d0fb74520dd79b6bf6003cb9cfc9dd0 to your computer and use it in GitHub Desktop.
Google Speech Recognition with API key + google-auth-library
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs'); | |
const { auth } = require('google-auth-library'); | |
const API_KEY = 'ADD YOUR API KEY HERE'; | |
const fileName = './audio.raw'; | |
// Reads a local audio file and converts it to base64 | |
const file = fs.readFileSync(fileName); | |
const audioBytes = file.toString('base64'); | |
// The audio file's encoding, sample rate in hertz, and BCP-47 language code | |
const audio = { | |
content: audioBytes, | |
}; | |
const config = { | |
encoding: 'LINEAR16', | |
sampleRateHertz: 16000, | |
languageCode: 'en-US', | |
}; | |
const request = { | |
audio: audio, | |
config: config | |
}; | |
const client = auth.fromAPIKey(API_KEY); | |
const url = 'https://speech.googleapis.com/v1/speech:recognize'; | |
client.request({ | |
url, | |
method: 'POST', | |
data: request | |
}) | |
.then(response => { | |
const transcription = response.data.results | |
.map(result => result.alternatives[0].transcript) | |
.join('\n'); | |
console.log(`Transcription: ${transcription}`); | |
}) | |
.catch(err => { | |
console.log('err :', err); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment