- Published on
Day23: Speech Synthesis
- Authors
- Name
- chick_playground
- @chick_playground
簡介: 如何使用 JavaScript 和 Web Speech API 來實現語音合成功能。
作品頁面:https://iris1114.github.io/javascript30/23_Speech-Synthesis/
HTML
- 包含一個
select
元素,用於選擇語音。 - 包含兩個
input
元素,用於調整語速和音調。 - 包含一個
textarea
元素,用於輸入要合成的文本。 - 包含兩個按鈕,用於控制語音播放和停止。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Speech Synthesis</title>
</head>
<body>
<div>
<select name="voice" id="voices">
<option value="">Select A Voice</option>
</select>
<label for="rate">Rate:</label>
<input name="rate" type="range" min="0" max="3" value="1" step="0.1" />
<label for="pitch">Pitch:</label>
<input name="pitch" type="range" min="0" max="2" step="0.1" />
<textarea name="text">Hello! I love JavaScript 👍</textarea>
<button id="stop">Stop!</button>
<button id="speak">Speak</button>
</div>
<script src="scripts.js"></script>
</body>
</html>
JavaScript
- 使用 JavaScript 和 Web Speech API 來實現語音合成功能,並控制語音播放和停止。
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
// 填充語音選項
function populateVoices() {
voices = this.getVoices()
voicesDropdown.innerHTML = voices
.filter((voice) => voice.lang.includes('en'))
.map((voice) => `<option value="${voice.name}">${voice.name} (${voice.lang})</option>`)
.join('')
}
// 設置語音
function setVoice() {
msg.voice = voices.find((voice) => voice.name === this.value)
toggle()
}
// 播放語音
function toggle(startOver = true) {
speechSynthesis.cancel()
if (startOver) {
speechSynthesis.speak(msg)
}
}
// 設置語速和音調
function setOption() {
msg[this.name] = this.value
toggle()
}
speechSynthesis.addEventListener('voiceschanged', populateVoices)
voicesDropdown.addEventListener('change', setVoice)
options.forEach((option) => option.addEventListener('change', setOption))
speakButton.addEventListener('click', toggle)
stopButton.addEventListener('click', () => toggle(false))
Note
- 使用
speechSynthesis.getVoices
來獲取可用的語音列表。 - 使用
SpeechSynthesisUtterance
來創建語音合成的對象。 - 使用
speechSynthesis.speak
來播放語音,使用speechSynthesis.cancel
來停止語音。