Text-to-speech based on Node.js

Text-to-speech based on Node.js

Node.js is a widely used server-side JavaScript development environment for a variety of text-to-speech applications. This article describes how to implement text-to-speech using Node.js.

Text-to-speech using Node.js

The first step in text-to-speech is to install Node.js. After the installation is successful, next create a file text-to-speech.js, edit and enter the following code:

// 导入文本转语音模块
const tts = require('@google-cloud/text-to-speech');

// 创建文本转语音客户端对象
const ttsClient = new tts.TextToSpeechClient();

// 设置文本转语音的请求参数
const request = {
    
    
  input: {
    
    text: 'Hello, world!'},
  // 语言
  voice: {
    
    languageCode: 'en-US', ssmlGender: 'NEUTRAL'},
  // 音频格式
  audioConfig: {
    
    audioEncoding: 'MP3'},
};	

// 执行文本转语音
ttsClient.synthesizeSpeech(request, (err, response) => {
    
    
  if (err) {
    
    
    console.error('ERROR:', err);
    return;
  }

  // 将语音保存为文件
  const writeFile = fs.createWriteStream('output.mp3');
  writeFile.write(response.audioContent);
  writeFile.end();
});

The meaning of the above code is: first we requireload @google-cloud/text-to-speechthe module, then create a text-to-speech client object ttsClient, and specify some request parameters, such as the text to be converted, the language of the audio, etc., and finally call ttsClientthe synthesizeSpeechmethod to write the result into output.mp3to .

Running the above code, we can generate an audio file output.mp3called , which is the result of text-to-speech. Play the audio file, and you can hear the robot's voice: "Hello, world!"

in conclusion

Through this article, we have learned how to use Node.js to realize the function of text-to-speech without complex code, and can quickly realize the purpose of text-to-speech.

Guess you like

Origin blog.csdn.net/weixin_50814640/article/details/129449503