Skip to content

Instantly share code, notes, and snippets.

@phsultan
Created April 12, 2018 09:34
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save phsultan/60b7b33270be54453252b759f141eabc to your computer and use it in GitHub Desktop.
Save phsultan/60b7b33270be54453252b759f141eabc to your computer and use it in GitHub Desktop.
Google Speech Recognition with API key + google-auth-library
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