首页 > 解决方案 > Google Text-to-speech - 如何从文件中读取文本输入?

问题描述

我在 Node.js 中使用 Google TextToSpeech API 从文本生成语音。我能够获得与为语音生成的文本同名的输出文件。但是,我需要稍微调整一下。我希望我可以同时生成多个文件。关键是我有,例如,5 个单词(或句子)要生成,例如 cat、dog、house、sky、sun。我想将它们分别生成到一个单独的文件中:cat.wav、dog.wav 等。

我还希望应用程序能够从 * .txt 文件中读取这些单词(每个单词/句子在 * .txt 文件的单独行上)。

有这种可能吗?下面我将粘贴 * .js 文件代码和我正在使用的 * .json 文件代码。

*.js

const textToSpeech = require('@google-cloud/text-to-speech');
const fs = require('fs');
const util = require('util');
const projectId = 'forward-dream-295509'
const keyFilename = 'myauth.json'
const client = new textToSpeech.TextToSpeechClient({ projectId, keyFilename });
const YourSetting = fs.readFileSync('setting.json');
async function Text2Speech(YourSetting) {
  const [response] = await client.synthesizeSpeech(JSON.parse(YourSetting));
  const writeFile = util.promisify(fs.writeFile);
  await writeFile(JSON.parse(YourSetting).input.text + '.wav', response.audioContent, 'binary');
  console.log(`Audio content written to file: ${JSON.parse(YourSetting).input.text}`);
}
Text2Speech(YourSetting);

*.json

{
  "audioConfig": {
    "audioEncoding": "LINEAR16",
    "pitch": -2,
    "speakingRate": 1
  },
  "input": {
    "text": "Text to Speech" 
  },
  "voice": {
    "languageCode": "en-US",
    "name": "en-US-Wavenet-D"
  }
}

我不太擅长编程。我在 google 上找到了一个关于如何执行此操作的教程,并对其进行了一些修改,以便保存文件的名称与生成的文本相同。

我将非常感谢您的帮助。阿雷克

标签: javascriptgoogle-apijson

解决方案


推荐阅读