溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么使用SpeechSynthesis實現文字自動播報

發(fā)布時間:2023-03-27 14:30:01 來源:億速云 閱讀:166 作者:iii 欄目:開發(fā)技術

這篇文章主要介紹“怎么使用SpeechSynthesis實現文字自動播報”,在日常操作中,相信很多人在怎么使用SpeechSynthesis實現文字自動播報問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”怎么使用SpeechSynthesis實現文字自動播報”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!

    一、關于SpeechSynthesis

    1、SpeechSynthesis簡介

    SpeechSynthesis是HTML5的一個新特性,基于SpeechSynthesis可以實現在客戶瀏覽器端進行動態(tài)文本的語音合成播放。在HTML5中和Web Speech相關的API實際上有兩類,一類是“語音識別(Speech Recognition)”,另外一個就是“語音合成(Speech Synthesis)”,這兩個名詞聽上去很高大上,實際上指的分別是“語音轉文字”,和“文字變語音”。而本文要介紹的就是這里的“語音合成-文字變語音”。為什么稱為“合成”呢?比方說你Siri發(fā)音“你好,世界!” 實際上是把“你”、“好”、“世”、“界”這4個字的讀音給合并在一起,因此,稱為“語音合成”。

    2、SpeechSynthesis的核心類

    怎么使用SpeechSynthesis實現文字自動播報

    SpeechSyntehesisUtteranc這個類主要用于控制合成聲音的屬性配置,比如主要內容,語音模板,語速等等,通過這個核心類控制。它的屬性信息如下:

    序號

    參數

    解釋

    1

    text

    要合成的文字內容,字符串

    2

    lang

    使用的語言,字符串, 例如:"zh-cn"

    3

    voiceURI

    指定希望使用的聲音和服務,字符串。

    4

    volume

    聲音的音量,區(qū)間范圍是0到1,默認是1

    5

    rate

    語速,數值,默認值是1,范圍是0.1到10,表示語速的倍數,例如2表示正常語速的兩倍。

    6

    pitch

    表示說話的音高,數值,范圍從0(最?。┑?(最大)。默認值為1

    核心方法如下表所示:

    序號

    方法名

    說明

    1

    onstart

    語音合成開始時候的回調。

    2

    onpause

    語音合成暫停時候的回調

    3

    onresume

    語音合成重新開始時候的回調

    4

    onend

    語音合成結束時候的回調

    5

    onmark

    Fired when the spoken utterance reaches a named SSML "mark" tag.

    其它更詳細的介紹可以參考以下地址Html Web API 接口。這里有更詳細的描述,還有詳細的示例。

    var synth = window.speechSynthesis;
    var voices = synth.getVoices();
     
    var inputForm = document.querySelector('form');
    var inputTxt = document.querySelector('input');
    var voiceSelect = document.querySelector('select');
     
    for(var i = 0; i < voices.length; i++) {
      var option = document.createElement('option');
      option.textContent = voices[i].name + ' (' + voices[i].lang + ')';
      option.value = i;
      voiceSelect.appendChild(option);
    }
     
    inputForm.onsubmit = function(event) {
      event.preventDefault();
     
      var utterThis = new SpeechSynthesisUtterance(inputTxt.value);
      utterThis.voice = voices[voiceSelect.value];
      synth.speak(utterThis);
      inputTxt.blur();
    }

    怎么使用SpeechSynthesis實現文字自動播報

    3、speechSynthesis對象

    speechSynthesis是實際調用SpeechSynthesisUtterance對象進行合成播報的。他的屬性和方法如下兩個表格描述。

    序號

    名稱

    描述

    1

    paused

    當SpeechSynthesis 處于暫停狀態(tài)時, Boolean (en-US) 值返回 true

    2

    pending

    當語音播放隊列到目前為止保持沒有說完的語音時, Boolean (en-US) 值返回 true 。

    3

    speaking

    當語音談話正在進行的時候,即使SpeechSynthesis處于暫停狀態(tài), Boolean (en-US) 返回 true 。

    怎么使用SpeechSynthesis實現文字自動播報

    var synth = window.speechSynthesis;
     
    var inputForm = document.querySelector('form');
    var inputTxt = document.querySelector('.txt');
    var voiceSelect = document.querySelector('select');
     
    var pitch = document.querySelector('#pitch');
    var pitchValue = document.querySelector('.pitch-value');
    var rate = document.querySelector('#rate');
    var rateValue = document.querySelector('.rate-value');
     
    var voices = [];
     
    function populateVoiceList() {
      voices = synth.getVoices();
     
      for(i = 0; i < voices.length ; i++) {
        var option = document.createElement('option');
        option.textContent = voices[i].name + ' (' + voices[i].lang + ')';
     
        if(voices[i].default) {
          option.textContent += ' -- DEFAULT';
        }
     
        option.setAttribute('data-lang', voices[i].lang);
        option.setAttribute('data-name', voices[i].name);
        voiceSelect.appendChild(option);
      }
    }
     
    populateVoiceList();
    if (speechSynthesis.onvoiceschanged !== undefined) {
      speechSynthesis.onvoiceschanged = populateVoiceList;
    }
     
    inputForm.onsubmit = function(event) {
      event.preventDefault();
     
      var utterThis = new SpeechSynthesisUtterance(inputTxt.value);
      var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name');
      for(i = 0; i < voices.length ; i++) {
        if(voices[i].name === selectedOption) {
          utterThis.voice = voices[i];
        }
      }
      utterThis.pitch = pitch.value;
      utterThis.rate = rate.value;
      synth.speak(utterThis);
     
      inputTxt.blur();
    }

    在了解了SpeechSynthesis的相關對象的屬性和方法之后,就可以用來實現自己的語音播報功能。下一節(jié)中重點描述。

    二、SpeechSynthesi文本實例合成

    1、新建test.html

    <!DOCTYPE html>
    <html>
     
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <title>網頁版文字轉語音朗讀功能</title>
            <style>
                article {margin: 0 auto;max-width: 800px;text-align: center;}
                textarea {max-width: 600px;width:100%;text-align: left;}
                button{border-radius: 3px;border: 1px solid #dddddd;height: 30px;width: 80px;cursor: pointer;}
            </style>
        </head>
     
        <body>
            <article>
                <h4 align="center">請在下面文本框中輸入要朗讀的文本:</h4>
                <p>
                    <textarea id="texts" rows="15" class="_play">本網頁版本語音合成播報支持Microsoft Edge等瀏覽器,不必連接網絡。</textarea>
                </p>
                <p>
                    <label>選擇播報語音:</label>
                    <select id="voiceSelect" onchange="play()"></select>
                </p>
                <button class="_search" onclick="play()">開始</button>
                <button onclick="resume()">繼續(xù)</button>
                <button onclick="pause()">暫停</button>
                <!-- <button onclick="cancel()">清除隊列</button> -->
                <button onclick="cls()">清空文本</button>
            </article>
        </body>
    </html>

    生成本地支持的語音模板,不同的瀏覽器獲取到的支持信息可能不一樣,大家可以根據實際情況添加,而且有的添加了也不一定支持播放。

    //創(chuàng)建選擇語言的select標簽
    function populateVoiceList() {
          voices = speechSynthesis.getVoices();
          for(i = 0; i < voices.length; i++) {
               var option = document.createElement('option');
               option.textContent = voices[i].name + ' (' + voices[i].lang + ')';
     
               if(voices[i].default) {
                  option.textContent += ' -- DEFAULT';
                }
               option.setAttribute('data-lang', voices[i].lang);
               option.setAttribute('data-name', voices[i].name);
               voiceSelect.appendChild(option);
          }
    }
     
    setTimeout(function() {
           populateVoiceList();
    }, 500) //

    2、定義相關播放方法

    if(!('speechSynthesis' in window)) {
        throw alert("對不起,您的瀏覽器不支持")
    }
     
    var _play = document.querySelector("._play"),
    to_speak = window.speechSynthesis,
    dataName, voiceSelect = document.querySelector("#voiceSelect"),
    voices = [];
     
    function play() {
      myCheckFunc();//檢查文本框是否為空
      cancel(); //
      to_speak = new SpeechSynthesisUtterance(_play.value);
     
      //to_speak.rate = 1.4;// 設置播放語速,范圍:0.1 - 10之間
     
      var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name');
      for(i = 0; i < voices.length; i++) {
      if(voices[i].name === selectedOption) {
            to_speak.voice = voices[i];
           }
       }
       window.speechSynthesis.speak(to_speak);
     }
     //暫停
    function pause() {
         myCheckFunc();//檢查文本框是否為空
         window.speechSynthesis.pause();
    }
    //繼續(xù)播放
    function resume() {
        myCheckFunc();//檢查文本框是否為空
        window.speechSynthesis.resume(); //繼續(xù)
    }
    //清除所有語音播報創(chuàng)建的隊列
    function cancel() {
        window.speechSynthesis.cancel();
    }
    //清空文本框
    function cls()  {
        document.getElementById("texts").value=""; 清空文本框
    }
    //檢查文本框是否為空
    function myCheckFunc() {
        let x;
        x = document.getElementById("texts").value;
        try {
            if (x === "")
                 throw "文本框為空";
             } catch (error) {
             alert( "提示" + error);
        }
    }

    3、本地語言支持

    //創(chuàng)建選擇語言的select標簽
    function populateVoiceList() {
        voices = speechSynthesis.getVoices();
        for(i = 0; i < voices.length; i++) {
            var option = document.createElement('option');
            option.textContent = voices[i].name + ' (' + voices[i].lang + ')';
     
            if(voices[i].default) {
                option.textContent += ' -- DEFAULT';
            }
            option.setAttribute('data-lang', voices[i].lang);
            option.setAttribute('data-name', voices[i].name);
            voiceSelect.appendChild(option);
        }
    }

    怎么使用SpeechSynthesis實現文字自動播報

    怎么使用SpeechSynthesis實現文字自動播報

    怎么使用SpeechSynthesis實現文字自動播報

    瀏覽器支持

    怎么使用SpeechSynthesis實現文字自動播報

    以下是瀏覽器的支持情況,從圖中可以看到它的瀏覽器支持是不太全的,但基本覆蓋了主流瀏覽器,從使用場景上來說基本可以完成覆蓋。

    怎么使用SpeechSynthesis實現文字自動播報

    到此,關于“怎么使用SpeechSynthesis實現文字自動播報”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續(xù)學習更多相關知識,請繼續(xù)關注億速云網站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>

    向AI問一下細節(jié)

    免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

    AI