Last active
April 30, 2022 16:51
-
-
Save meganetaaan/9f4d9cbc0ce8b3cfd48f8f035d07f24d to your computer and use it in GitHub Desktop.
Speech generation via Google Text-to-Speech API
This file contains 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
/** | |
https://cloud.google.com/text-to-speech/docs/create-audio-text-client-libraries#client-libraries-usage-nodejs | |
### USAGE | |
* [Setup your googleplatform project](https://cloud.google.com/text-to-speech/docs/before-you-begin) | |
and download a service account json key. | |
* run below. | |
``` | |
npm init | |
npm install @google-cloud/text-to-speech | |
env GOOGLE_APPLICATION_CREDENTIALS=/path/to/your/service-account-key.json node generate-speech.js | |
``` | |
**/ | |
// Imports the Google Cloud client library | |
import textToSpeech from '@google-cloud/text-to-speech' | |
// Import other required libraries | |
import fs from 'fs' | |
import util from 'util' | |
const SAMPLE_RATE = 11025; | |
// Creates a client | |
const client = new textToSpeech.TextToSpeechClient(); | |
async function quickStart() { | |
// The text to synthesize | |
const text = 'hello, world!'; | |
// Construct the request | |
const request = { | |
input: { text: text }, | |
// Select the language and SSML voice gender (optional) | |
voice: { languageCode: 'en-US', name: 'en-US-Wavenet-F', ssmlGender: 'NEUTRAL' }, | |
// select the type of audio encoding | |
audioConfig: { audioEncoding: 'LINEAR16', sampleRateHertz: SAMPLE_RATE }, | |
}; | |
// Performs the text-to-speech request | |
const [response] = await client.synthesizeSpeech(request); | |
// Write the binary audio content to a local file | |
const writeFile = util.promisify(fs.writeFile); | |
await writeFile('output.wav', response.audioContent, 'binary'); | |
console.log('Audio content written to file: output.wav'); | |
} | |
quickStart(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment