Web Speech API 實(shí)現(xiàn)語音合成和語音識(shí)別

MDN 使用 Web Speech API 主要包含以下兩部分:

基本用法參考:張?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分

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容