SpeechSynthesisUtterance
- SpeechSynthesisUtterance是HTML5中新增的API,用於將指定文字合成爲對應的語音.也包含一些配置項,指定如何去閱讀(語言,音量,音調)等
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text" id="textMsg" value="有新的訂單,請及時處理">
<button onclick="speak()">播放</button>
<button onclick="pause()">暫停</button>
<button onclick="resume()">繼續播放</button>
<button onclick="cancel()">取消播放</button>
<script>
var speech = new SpeechSynthesisUtterance();
// 播放
function speak() {
// speech.pitch = 1 // 獲取並設置話語的音調(值越大越尖銳,越低越低沉)
// speech.rate = 5 // 獲取並設置說話的速度(值越大語速越快,越小語速越慢)
// speech.voice = 10 // 獲取並設置說話的聲音
// speech.volume = 1 // 獲取並設置說話的音量
// speech.lang = speechSynthesis.getVoices()[0] // 設置播放語言,測試沒效果
// speech.cancel() // 刪除隊列中全部的語音.若是正在播放,則直接中止
speech.text = textMsg.value // 獲取並設置說話時的文本
speechSynthesis.speak(speech);
}
// 暫停
function pause() {
speechSynthesis.pause()
}
// 繼續播放
function resume() {
speechSynthesis.resume()
}
// 取消播放
function cancel() {
speechSynthesis.cancel()
}
</script>
</body>
</html>