23 - Speech Synthesis
主題
使用SpeechSynthesisUtterance
及speechSynthesis
來使文字轉語音。
上次有做過語音轉文字的練習[[20 - Speech Detection]],
這次則是要使用文字轉語音,透過介面中的輸入欄位來轉語音播放,
並可透過設定好的控制條來變更語音速率/音準。
步驟
Step1. 取得頁面元素並設置SpeechSynthesisUtterance
1 2 3 4 5 6 7 8
| const msg = new SpeechSynthesisUtterance(); let voices = []; const voicesDropdown = document.querySelector('[name="voice"]'); const options = document.querySelectorAll('[type="range"], [name="text"]'); const speakButton = document.querySelector('#speak'); const stopButton = document.querySelector('#stop');
msg.text = document.querySelector('[name="text"]').value
|
Step2. 設定語音播放語系選單
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| function populateVoices() { voices = this.getVoices(); voicesDropdown.innerHTML = voices .filter(voice => voice.lang.includes('zh') || voice.lang.includes('en')) .map(voice => `<option value=${voice.name}>${voice.name} (${voice.lang})</option>`) .join(''); }
speechSynthesis.addEventListener('voiceschanged', populateVoices);
|
Step3. 播放與功能設定
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| function toggle(starOver = true) { speechSynthesis.cancel(); if (starOver) { speechSynthesis.speak(msg); } }
function setVoice() { msg.voice = voices.find(voice => voice.name === this.value); toggle(); }
function setOption() { msg[this.name] = this.value; toggle(); }
voicesDropdown.addEventListener('change', setVoice);
options.forEach(option => option.addEventListener('change', setOption));
speakButton.addEventListener('click', toggle);
stopButton.addEventListener('click', () => toggle(false));
|
語法&備註
SpeechSynthesisUtterance
可以設置語音服務應讀取的文字內容及播放的細節(語系、速率、音量..等屬性)
參閱:MDN-Element.getBoundingClientRect()
SpeechSynthesis
執行語音服務的主要功能,包含了播放、暫停..等屬性
參閱:MDN-SpeechSynthesis
[DEMO]