Web Speech API 实现语音合成和语音识别

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

基本用法参考:张鑫旭——HTML5语音合成Speech Synthesis API简介
SpeechSynthesisUtterance属性用法主要包括:text 属性、lang属性、voice属性(指定话语的说话音量。它的范围是0到1(含0和1))、rate属性(指定话语的语速。这是相对于此语音的默认速率。严格禁止小于0.1或大于10的值)、pitch属性(指定发声的说话音调。范围在0到2之间(含0和2)。

一个简单的 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>
        // 接下来是运行这个函数,我们做如下代码工作。因为Firefox不支持SpeechSynthesis.onvoiceschanged ,所以很常规地只是返回语音对象列表当SpeechSynthesis.getVoices() 被触发。但是 Chrome 就有点不同了,在SpeechSynthesis.getVoices() 被触发时,先要等待事件触发(有点绕~按照下面代码,populateVoiceList 函数在Firefox运行一次,在Chrome中运行两次):
        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>

千万注意的一点:因为 getVoice 方法里面返回的值有国家,所以做多语言的语音挺有用的,但是如果这样使用,getVoice 方法会直接返回空数组。

function populateVoiceList() {
    const synth = window.speechSynthesis;
    const voices = synth.getVoices();

    console.log(voices);
};
populateVoiceList();

原因如下:

因为Firefox不支持SpeechSynthesis.onvoiceschanged ,所以很常规地只是返回语音对象列表当SpeechSynthesis.getVoices() 被触发。但是 Chrome 就有点不同了,在SpeechSynthesis.getVoices() 被触发时,先要等待事件触发(有点绕~按照下面代码,populateVoiceList 函数在Firefox运行一次,在Chrome中运行两次):

现修改如下:

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点41分

推荐阅读更多精彩内容