MDN 使用 Web Speech API 主要包含以下兩部分:
- Speech recognition 語音識(shí)別
- Speech synthesis 語音合成
基本用法參考:張?chǎng)涡瘛狧TML5語音合成Speech Synthesis API簡(jiǎn)介
SpeechSynthesisUtterance屬性用法主要包括:text 屬性、lang屬性、voice屬性(指定話語的說話音量。它的范圍是0到1(含0和1))、rate屬性(指定話語的語速。這是相對(duì)于此語音的默認(rèn)速率。嚴(yán)格禁止小于0.1或大于10的值)、pitch屬性(指定發(fā)聲的說話音調(diào)。范圍在0到2之間(含0和2)。
一個(gè)簡(jiǎn)單的 demo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h3 id="content">
Want to make a personal website or blog and share it with the world? Then you’ve come to the right place! This is the only guide you’ll need to get started with Jekyll and host your site for free on GitHub Pages. I’ll take you from zero to hero with Jekyll and help you understand all the fundamentals.
</h3>
<button id="btn">播放</button>
<script>
// 接下來是運(yùn)行這個(gè)函數(shù),我們做如下代碼工作。因?yàn)镕irefox不支持SpeechSynthesis.onvoiceschanged ,所以很常規(guī)地只是返回語音對(duì)象列表當(dāng)SpeechSynthesis.getVoices() 被觸發(fā)。但是 Chrome 就有點(diǎn)不同了,在SpeechSynthesis.getVoices() 被觸發(fā)時(shí),先要等待事件觸發(fā)(有點(diǎn)繞~按照下面代碼,populateVoiceList 函數(shù)在Firefox運(yùn)行一次,在Chrome中運(yùn)行兩次):
const btn = document.getElementById("btn");
function getVoices(){
const synth = window.speechSynthesis;
let voices = synth.getVoices().filter(voice => voice.lang.startsWith(document.querySelector('html').lang));
if (voices.length == 0) return;
let utterThis = new SpeechSynthesisUtterance(document.querySelector('#content').textContent);
utterThis.volume = 1;
console.log(utterThis);
synth.speak(utterThis);
};
btn.addEventListener("click",getVoices);
</script>
</body>
</html>
千萬注意的一點(diǎn):因?yàn)?getVoice 方法里面返回的值有國家,所以做多語言的語音挺有用的,但是如果這樣使用,getVoice 方法會(huì)直接返回空數(shù)組。
function populateVoiceList() {
const synth = window.speechSynthesis;
const voices = synth.getVoices();
console.log(voices);
};
populateVoiceList();
原因如下:
因?yàn)镕irefox不支持
SpeechSynthesis.onvoiceschanged,所以很常規(guī)地只是返回語音對(duì)象列表當(dāng)SpeechSynthesis.getVoices()被觸發(fā)。但是 Chrome 就有點(diǎn)不同了,在SpeechSynthesis.getVoices()被觸發(fā)時(shí),先要等待事件觸發(fā)(有點(diǎn)繞~按照下面代碼,populateVoiceList函數(shù)在Firefox運(yùn)行一次,在Chrome中運(yùn)行兩次):
現(xiàn)修改如下:
function populateVoiceList() {
const synth = window.speechSynthesis;
const voices = synth.getVoices();
console.log(voices);
};
populateVoiceList();
// onvoiceschanged===null;
if (speechSynthesis.onvoiceschanged !== undefined) {
speechSynthesis.onvoiceschanged = populateVoiceList;
}
2020年4月6日22點(diǎn)41分