Windows平臺Node.js實現文本轉語音TTS

最新有個需求,想在Windows平臺上用Node.js實現文本轉語音 (Text to Speech, TTS) 功能,實現過程當中走了一些彎路,總結一下,作個記錄。javascript

由於不要求聽起來多天然,也不考慮跨平臺,因此就打算本身實現一下。PowerShell能夠調用系統的語音API,代碼以下:java

Add-Type -AssemblyName System.speech;
$speak = New-Object System.Speech.Synthesis.SpeechSynthesizer;
$speak.Rate = 5; # 語速,-10 ~ 10,-10最慢,10最快
$speak.Speak('別不信')
複製代碼

在PowerShell中運行這段代碼,就能夠聽到語速稍快的「別不信」(語音)了。shell

在Node.js中怎麼用呢?因爲PowerShell默認是GBK編碼,考慮編碼轉換,以下:bash

const { exec } = require('child_process');
const iconv = require('iconv-lite');

exec(`powershell.exe Add-Type -AssemblyName System.speech; $speak = New-Object System.Speech.Synthesis.SpeechSynthesizer; $speak.Rate = 5; $speak.Speak([Console]::In.ReadLine()); exit`).stdin.end(iconv.encode('別不信', 'gbk'));
複製代碼

這樣就用最簡單的代碼實現了TTS功能。ui

我的技術博客 biebu.xin,原文連接——Windows平臺Node.js實現文本轉語音TTS編碼

相關文章
相關標籤/搜索