探索Google的Node.js文本转语音库:轻松实现自然语音合成
warning:
这篇文章距离上次修改已过202天,其中的内容可能已经有所变动。
// 引入文本转语音库
const textToSpeech = require('@google-cloud/text-to-speech');
// 创建一个客户端实例
const client = new textToSpeech.TextToSpeechClient();
// 异步函数:将文本转换为音频
async function synthesizeText(text) {
const request = {
input: {text: text},
// 选择合适的语音人声
voice: {languageCode: 'en-US', ssmlGender: 'NEUTRAL'},
// 设置音频编码和输出路径
audioConfig: {audioEncoding: 'MP3'},
};
const [response] = await client.synthesizeSpeech(request);
return response.audioContent;
}
// 使用示例
const text = 'Hello, world!';
synthesizeText(text)
.then((audioContent) => {
// 将音频内容写入文件
const fs = require('fs');
fs.writeFileSync('output.mp3', audioContent, 'binary');
console.log('Audio content written to file');
})
.catch(err => {
console.error('Synthesize error:', err);
});
这段代码首先引入了Google的文本转语音库,然后创建了一个客户端实例。synthesizeText
函数接受一个文本字符串作为输入,并返回对应的音频内容。然后,我们可以将这个音频内容保存到文件中,实现了文本转语音的功能。
评论已关闭