JavaScript文字轉(zhuǎn)語音_SpeechSynthesisUtterance語音合成的使用

實例對象屬性
lang 獲取并設置話語的語言
pitch 獲取并設置話語的音調(diào)(值越大越尖銳,越低越低沉)
rate 獲取并設置說話的速度(值越大語速越快,越小語速越慢)
text 獲取并設置說話時的文本
voice 獲取并設置說話的聲音
volume 獲取并設置說話的音量
SpeechSynthesis方法
speak() 將對應的實例添加到語音隊列中
cancel() 刪除隊列中所有的語音.如果正在播放,則直接停止
pause() 暫停語音
resume() 恢復暫停的語音
getVoices 獲取支持的語言數(shù)組.?注意:必須添加在voiceschanged事件中才能生效
實例對象方法
onpause – 語音合成暫停時候的回調(diào)。
onresume – 語音合成重新開始時候的回調(diào)。
onend – 語音合成結(jié)束時候的回調(diào)。
簡單實現(xiàn)
let utterThis = new SpeechSynthesisUtterance('你好,世界!');speechSynthesis.speak(utterThis);
let utterThis = new SpeechSynthesisUtterance();utterThis.text = '你好,世界!';utterThis.lang = 'zh';//漢語utterThis.rate = 0.7;//語速speechSynthesis.speak(utterThis);
項目實戰(zhàn)
<div class="voiceinator"><h1>聽說 5000h1><select name="voice" id="voices"><option value="">Select A Voiceoption>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">你好 給你點?textarea><button id="stop">Stop!button><button id="speak">Speakbutton>div>
const synth = window.speechSynthesisconst 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 = '你好 給你點?'msg.lang = 'zh-CN'synth.addEventListener('voiceschanged',getSupportVoices)speakButton.addEventListener('click',throttle(handleSpeak,1000))stopButton.addEventListener('click',handleStop)options.forEach(e => e.addEventListener('change',handleChange))function getSupportVoices() {voices = synth.getVoices()voices.forEach(e => {const option = document.createElement('option')option.value = e.langoption.text = e.namevoicesDropdown.appendChild(option)})}function handleSpeak(e) {msg.lang = voicesDropdown.selectedOptions[0].valuesynth.speak(msg)}function handleStop(e) {synth.cancel(msg)}function handleChange(e) {msg[this.name] = this.value}function throttle(fn,delay) {let last = 0return function() {const now = new Date()if(now - last > delay) {fn.apply(this,arguments)last = now}}}
代碼解讀
遇到問題
window.speechSynthesis.cancel()
if(!!window.SpeechSynthesisUtterance){console.log("請使用其他瀏覽器!")}

評論
圖片
表情
