網路上的window.speechSynthesis
教學主要都只有說切換指定語言
像是這樣就能切換成中文語音:
const synth = window.speechSynthesis;
const speak = (msg) => {
let u = new SpeechSynthesisUtterance();
u.lang = 'zh-TW';
u.text = msg;
synth.speak(u);
};
speak("你要讀出的中文內容1");
speak("你要讀出的中文內容2");
但是這種寫法在系統有支援多種語音的情況下只會選擇系統預設語音
- win7繁中 - 無支援中文語音
- 2020/8月補充: 現在win7繁中版可以去載Chromium版的Edge來使用微軟中文語音
- win7簡中 - 有支援微軟中文語音(系統預設)
- win10 - 簡繁中都有支援微軟中文語音(系統預設)
如果想要切換成其他語音(例如Chrome才有的Google中文語音)
就要另外再寫
const synth = window.speechSynthesis;
const speak = (msg) => {
let u = new SpeechSynthesisUtterance();
//u.lang = 'zh-TW'; //這句絕對不要用
u.text = msg;
// 用 synth.getVoices() 取得支援的語音列表
// 要注意網頁開啟後首次執行 window.speechSynthesis 後才會把語音功能載入
// 大概要花幾秒鐘的時間才能完全載入,再來才能正確取得語音列表
// 所以要想辦法延遲 synth.getVoices(); 的執行時間
//
// 或是使用下面的事件偵測
// (這個事件在載入過程會被觸發多次,很難用,他是偵測changed不是偵測完全載入完成,
// 但這是window.speechSynthesis裡唯一的一個事件偵測,沒其他選擇)
// var voices;
// window.speechSynthesis.onvoiceschanged = function() {
// voices = synth.getVoices();
// // 注意 speak() 不要直接寫在這裡,不然會被重覆觸發多次
// };
let voices = synth.getVoices();
for(let index = 0; index < voices.length; index++) {
/*
"Google US English"
"Google 日本語"
"Google 普通话(中国大陆)"
"Google 粤語(香港)"
"Google 國語(臺灣)"
*/
//console.log(this.voices[index].name);
if(voices[index].name == "Google 國語(臺灣)"){
//u.lang = 'zh-TW'; //這句絕對不要用
//要使用Google中文語音的話請不要再用u.lang指定語言
//不然可能又會被切回系統預設的中文語音
u.voice = voices[index];
break;
}else{
//如果沒有則使用預設中文語音
u.lang = 'zh-TW';
}
}
synth.speak(u);
};
speak("你要讀出的中文內容1");
speak("你要讀出的中文內容2");
window.speechSynthesis是瀏覽器內原生的語音功能,詳細用法可以看以下MDN的教學文件
- window.speechSynthesis
- SpeechSynthesisUtterance
- window.speechSynthesis.onvoiceschanged
- Stack Overflow上關於
window.speechSynthesis.onvoiceschanged
的討論
- Stack Overflow上關於
- 列出瀏覽器有支援哪些語音和測試語音的小工具