Skip to content

Instantly share code, notes, and snippets.

@navix
Created July 17, 2020 16:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save navix/1a713e459afdc2f778e1cf981184742f to your computer and use it in GitHub Desktop.
Save navix/1a713e459afdc2f778e1cf981184742f to your computer and use it in GitHub Desktop.
google text-to-speech
import { existsSync, mkdirSync } from 'fs';
import { resolve } from 'path';
import { config } from '../config';
export async function processTextToSpeech(ssml: string, filename: string) {
// Check media dir
const dirPath = resolve(config.main.storePath);
if (!existsSync(dirPath)) {
mkdirSync(dirPath);
}
// Imports the Google Cloud client library
const textToSpeech = require('@google-cloud/text-to-speech');
// Import other required libraries
const fs = require('fs');
const util = require('util');
// Creates a client
const client = new textToSpeech.TextToSpeechClient();
// Construct the request
const request = {
input: {ssml},
// Select the language and SSML Voice Gender (optional)
voice: {languageCode: 'uk-UA', ssmlGender: 'NEUTRAL'},
// Select the type of audio encoding
audioConfig: {audioEncoding: 'MP3'},
};
// 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(resolve(dirPath, `${filename}.mp3`), response.audioContent, 'binary');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment