最近因为工作比较忙,没什么进度,这几天来恶补一下,今天要做的功能是使用Web Speech的一个API SpeechSynthesisUtterance搭配SpeechSynthesis,来製作一个可侦测各国文字,并利用语音来输出声音的功能。
SpeechSynthesisUtterance:
为 Web Speech API,可以藉由它读出指定的文字,还可以输出语音,设定语言,调整音量、音调,等同new一个语音合成器。
SpeechSynthesis:
就是用来控制语音的播放和暂停及移除语音资讯的 API。
首先将new 出我们的语音合成器,再来我们增听voiceschanged事件,当speechSynthesis 物件中的 SpeechSynthesisVoice 清单改变时,就会触发该事件。
const utterance = new SpeechSynthesisUtterance(); speechSynthesis.addEventListener('voiceschanged', populateVoices);
再来将将语音选项设置至下拉选单中,并在全域环境设置一个let voices=[],来储存我们所有语音的阵列。
function populateVoices(e) { // 利用 SpeechSynthesis.getVoices()方法,取得包含所有SpeechSynthesisVoice 物件的阵列,而这些物件表示当前设备上可用之语音 voices = this.getVoices(); console.log(voices); // 获取所有可用之语音。 // 0: SpeechSynthesisVoice {voiceURI: "Microsoft Hanhan Desktop - Chinese (Taiwan)", name: "Microsoft Hanhan Desktop - Chinese (Taiwan)", lang: "zh-TW", localService: true, default: true}1: SpeechSynthesisVoice {voiceURI: "Microsoft Zira Desktop - English (United States)", name: "Microsoft Zira Desktop - English (United States)", lang: "en-US", localService: true, default: false}2: SpeechSynthesisVoice {voiceURI: "Google Deutsch", name: "Google Deutsch", lang: "d // 将可用之语音显示在下拉选单 voicesDropdown.innerHTML = voices // 可指定要听的语言(ex:en,zh) // .filter(voice => voice.lang.includes('zh')) .map(voice => `<option value="${voice.name}">${voice.name} (${voice.lang})</option>`); }
*= 选取器(可获取开头为...) / ,选取器(等同于or)
// 获取并设置所要播放语音的文字 utterance.text = document.querySelector('[name="text"]').value; const voicesDropdown = document.querySelector('[name="voice"]'); // 获取可调整range的pitch,rate // ,选取器等同于or const options = document.querySelectorAll('[type="range"], [name="text"]'); // 播放键、停止键 const speakButton = document.querySelector('#speak'); const stopButton = document.querySelector('#stop'); // * =可获取开头为...的class,但少用因为会影响效能 const test = document.querySelectorAll('[class * =col]');
当我们切换语音时,获取更换为我们要播放的语音。
// 设置所切换之语音 function setVoice() { // SpeechSynthesisUtterance.voice设置所要说的语音 console.log(utterance); utterance.voice = voices.find(voice => voice.name === this.value); play(); } // 当下拉切换语音时 voicesDropdown.addEventListener('change', setVoice);
当range,pitch的range有改变时触发。
// 改变utterance的rate,pitch属性的值 function setOption() { console.log(this.name, this.value); // pitch(语调) , 1.1 or rate(语速) 0.7 utterance[this.name] = this.value; play(); } options.forEach(option => option.addEventListener('change', setOption));
按下播放键,会将上个语音中断并重新播放新选之语音,而按下暂停会停止播放。
// 播放语音 function play() { stop(); // 将语音添加至语音序列中,当其他语音结束时,就播放他 speechSynthesis.speak(utterance); } // 停止语音 function stop() { // 暂停原本在讲的语音 speechSynthesis.cancel(); } speakButton.addEventListener('click', play); stopButton.addEventListener('click', stop);