[程式碼&DEMO] [HackMD完整筆記]
使用SpeechSynthesisUtterance物件,將文字轉為語音,並可透過頁面控制條去調整講話速度(rate)及音頻(pitch)的高低。
**STEP1 **
//建立SpeechSynthesisUtterance物件
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');
// 使頁面中的輸入欄位的值成為SpeechSynthesisUtterance要用的值
msg.text = document.querySelector('[name="text"]').value;
** STEP2 **
function populateVoices() {
voices = this.getVoices();
// 用join來合併且消除原本陣列的逗點
voicesDropdown.innerHTML = voices
// 用filter篩選出只有en的語系
.filter(voice => voice.lang.includes('en'))
// 篩選後的陣列用map把資料組成html的一個新標籤
.map(voice => `<option value="${voice.name}">${voice.name} (${voice.lang})</option>`)
.join('');
}
** STEP3 **
// 設定選擇的發音語系
function setVoice() {
msg.voice = voices.find(voice => voice.name === this.value);
toggle();
}
//設定一個toggle方法,做為驅動說話的開關
function toggle(startOver = true) {
speechSynthesis.cancel();
if (startOver) {
speechSynthesis.speak(msg);
}
}
// 設定速率和音準
function setOption() {
console.log(this.name, this.value);
msg[this.name] = this.value;
toggle();
}
** STEP4 **
speechSynthesis.addEventListener('voiceschanged', populateVoices);
// 監聽語系的選單,選擇後切換語系
voicesDropdown.addEventListener('change', setVoice);
options.forEach(option => option.addEventListener('change', setOption));
// 播放按鈕
speakButton.addEventListener('click', toggle);
// 停止按鈕
stopButton.addEventListener('click', () => toggle(false));
操作SpeechSynthesisUtterance()物件,執行語音服務的主要功能,包括播放、暫停等屬性。
speechSynthesis.speck()
speechSynthesis.cancel()
speechSynthesis.pause
speechSynthesis.getVoices()
speechSynthesis.resume()