Skip to content

Instantly share code, notes, and snippets.

@phsultan
Created April 12, 2018 09:36
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save phsultan/794c41f1d540611821f34ab070d41bdf to your computer and use it in GitHub Desktop.
Save phsultan/794c41f1d540611821f34ab070d41bdf to your computer and use it in GitHub Desktop.
Google Speech Recognition with API key + axios
const fs = require('fs');
const axios = require('axios');
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 apiKey = API_KEY;
const url = `https://speech.googleapis.com/v1/speech:recognize?key=${apiKey}`;
axios.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