如何解决Google Text-to-speech - 从 txt 文件的各行加载文本
我在 Node.js 中使用 Google TextToSpeech API 从文本生成语音。我能够获得与为语音生成的文本同名的输出文件。但是,我需要稍微调整一下。我希望我可以同时生成多个文件。关键是,例如,我有 5 个单词(或句子)要生成,例如猫,狗,房子,天空,太阳。我想将它们分别生成到一个单独的文件中: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 上找到了一个关于如何执行此操作的教程,并对其稍作修改,以便保存文件的名称与生成的文本相同。
非常感谢您的帮助。 阿雷克
解决方法
开始吧 - 我还没有测试过它,但这应该显示如何读取文本文件,拆分为每一行,然后使用设置的并发在它上面运行 tts。它使用您需要添加到项目中的 p-any 和 filenamify npm 包。请注意,谷歌可能有 API 节流或速率限制,我在这里没有考虑到 - 如果有问题,可以考虑使用 p-throttle 库。
// https://www.npmjs.com/package/p-map
const pMap = require('p-map');
// https://github.com/sindresorhus/filenamify
const filenamify = require('filenamify');
const textToSpeech = require('@google-cloud/text-to-speech');
const fs = require('fs');
const path = require('path');
const projectId = 'forward-dream-295509'
const keyFilename = 'myauth.json'
const client = new textToSpeech.TextToSpeechClient({ projectId,keyFilename });
const rawSettings = fs.readFileSync('setting.json',{ encoding: 'utf8'});
// base data for all requests (voice,etc)
const yourSetting = JSON.parse(rawSettings);
// where wav files will be put
const outputDirectory = '.';
async function Text2Speech(text,outputPath) {
// include the settings in settings.json,but change text input
const request = {
...yourSetting,input: { text }
};
const [response] = await client.synthesizeSpeech(request);
await fs.promises.writeFile(outputPath,response.audioContent,'binary');
console.log(`Audio content written to file: ${text} = ${outputPath}`);
// not really necessary,but you could return something if you wanted to
return response;
}
// process a line of text - write to file and report result (success/error)
async function processLine(text,index) {
// create output path based on text input (use library to ensure it's filename safe)
const outputPath = path.join(outputDirectory,filenamify(text) + '.wav');
const result = {
text,lineNumber: index,path: outputPath,isSuccess: null,error: null
};
try {
const response = await Text2Speech(text,outputPath);
result.isSuccess = true;
} catch (error) {
console.warn(`Failed: ${text}`,error);
result.isSuccess = false;
result.error = error;
}
return result;
}
async function processInputFile(filepath,concurrency = 3) {
const rawText = fs.readFileSync(filepath,{ encoding: 'utf8'});
const lines = rawText
// split into one item per line
.split(/[\r\n]+/)
// remove surrounding whitespace
.map(s => s.trim())
// remove empty lines
.filter(Boolean);
const results = await pMap(lines,processLine,{ concurrency });
console.log('Done!');
console.table(results);
}
// create sample text file
const sampleText = `Hello World
cat
dog
another line of text`;
fs.writeFileSync('./my-text-lines.txt',sampleText);
// process each line in the text file,3 at a time
processInputFile('./my-text-lines.txt',3);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。