tardis-bot/tts/google/index.js

36 lines
1.3 KiB
JavaScript

const BaseEngine = require('../BaseEngine')
const sdk = require('@google-cloud/text-to-speech');
const fs = require('fs');
const util = require('util');
module.exports = class GoogleCloudTTS extends BaseEngine {
constructor() {
super('google', 'Google Cloud TTS', 'wav');
this.client = new sdk.TextToSpeechClient();
this.client.initialize();
this.voices = {};
this.populateVoiceList();
}
async populateVoiceList() {
const [result] = await this.client.listVoices({});
const voiceList = result.voices;
voiceList.forEach((voice) => {
this.voices[voice.name.toLowerCase()] = { name: voice.name, lang: voice.languageCodes[0] };
});
}
getDefaultVoice() {
return 'en-US-Wavenet-A';
}
async getSpeechFile(text, filepath, voice = this.getDefaultVoice(), params = {}) {
const request = {
input: { text: text },
voice: { name: this.voices[voice].name, languageCode: this.voices[voice].lang },
audioConfig: { audioEncoding: 'LINEAR16' },
};
let [response] = await this.client.synthesizeSpeech(request);
const writeFile = util.promisify(fs.writeFile);
await writeFile(filepath, response.audioContent, 'binary');
return filepath;
}
}