<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          JavaScript文字轉(zhuǎn)語音_SpeechSynthesisUtterance語音合成的使用

          共 3366字,需瀏覽 7分鐘

           ·

          2021-12-14 17:49

          在做項目的過程中,遇到場景是客戶要求播放語音的場景,這里需要js來實現(xiàn)文字轉(zhuǎn)語音播放的功能。在不使用第三方API接口(這種方式需要外網(wǎng)),能想到的也就是利用html5的個API:SpeechSynthesis。
          SpeechSynthesis用于將指定文字合成為對應的語音.也包含一些配置項,指定如何去閱讀(語言,音量,音調(diào))等等。

          實例對象屬性

          • lang 獲取并設置話語的語言

          • pitch 獲取并設置話語的音調(diào)(值越大越尖銳,越低越低沉)

          • rate 獲取并設置說話的速度(值越大語速越快,越小語速越慢)

          • text 獲取并設置說話時的文本

          • voice 獲取并設置說話的聲音

          • volume 獲取并設置說話的音量

          SpeechSynthesis方法

          • speak() 將對應的實例添加到語音隊列中

          • cancel() 刪除隊列中所有的語音.如果正在播放,則直接停止

          • pause() 暫停語音

          • resume() 恢復暫停的語音

          • getVoices 獲取支持的語言數(shù)組.?注意:必須添加在voiceschanged事件中才能生效

          實例對象方法

          onstart – 語音合成開始時候的回調(diào)。
          onpause – 語音合成暫停時候的回調(diào)。
          onresume – 語音合成重新開始時候的回調(diào)。
          onend – 語音合成結(jié)束時候的回調(diào)。

          簡單實現(xiàn)

          先從最簡單的例子說起,如果想讓瀏覽器讀出“你好,世界!”的聲音,可以下面的js代碼:
          let utterThis = new SpeechSynthesisUtterance('你好,世界!');speechSynthesis.speak(utterThis);
          只需要這么一點代碼就足夠了,大家可以在自己瀏覽器的控制臺里面運行上面兩行代碼,看看有沒有讀出聲音。
          除了使用speak方法,我們還可以實例對象屬性text,因此上面的代碼也可以寫成:
          let utterThis = new SpeechSynthesisUtterance();utterThis.text = '你好,世界!';utterThis.lang = 'zh';//漢語utterThis.rate = 0.7;//語速speechSynthesis.speak(utterThis);

          項目實戰(zhàn)

          html:
          <div class="voiceinator"> <h1>聽說 5000h1> <select name="voice" id="voices"> <option value="">Select A Voiceoption> select> <label for="rate">Rate:label> <input name="rate" type="range" min="0" max="3" value="1" step="0.1"> <label for="pitch">Pitch:label> <input name="pitch" type="range" min="0" max="2" step="0.1"> <textarea name="text">你好 給你點?textarea> <button id="stop">Stop!button> <button id="speak">Speakbutton>div>
          JavaScript:
          const synth = window.speechSynthesisconst msg = new SpeechSynthesisUtterance()let voices = []const voicesDropdown = document.querySelector('[name="voice"]')const options = document.querySelectorAll('[type="range"], [name="text"]')const speakButton = document.querySelector('#speak')const stopButton = document.querySelector('#stop')
          msg.text = '你好 給你點?'msg.lang = 'zh-CN'
          synth.addEventListener('voiceschanged',getSupportVoices)speakButton.addEventListener('click',throttle(handleSpeak,1000))stopButton.addEventListener('click',handleStop)options.forEach(e => e.addEventListener('change',handleChange))
          function getSupportVoices() { voices = synth.getVoices() voices.forEach(e => { const option = document.createElement('option') option.value = e.lang option.text = e.name voicesDropdown.appendChild(option) })}function handleSpeak(e) { msg.lang = voicesDropdown.selectedOptions[0].value synth.speak(msg)}function handleStop(e) { synth.cancel(msg)}function handleChange(e) { msg[this.name] = this.value}function throttle(fn,delay) { let last = 0 return function() { const now = new Date() if(now - last > delay) { fn.apply(this,arguments) last = now } }}

          代碼解讀

          html部分:
          頁面布局方面就是通過select下拉菜單選擇需要轉(zhuǎn)換為什么語言,具體包括什么語言是通過js動態(tài)加載的。
          其次分別用兩個input的滑動來選擇語音播報的速度和音調(diào)。
          通過修改textarea來設置需要播報的文字內(nèi)容。
          最后通過按鈕來控制語音的播報和停止。
          JS部分:
          首先通過const synth = window.speechSynthesis來創(chuàng)建語音,用const msg = new SpeechSynthesisUtterance()來創(chuàng)建文本實例設置默認播報的文本和語言:msg.text和msg.lang。
          通過voiceschanged事件來動態(tài)獲取支持的語言種類,并生成options添加到html中.其中最主要的方法就是synth.getVoices()獲取.各位可以通過自行打印獲取到的數(shù)組查看具體包含的屬性。
          創(chuàng)建按鈕點擊事件,分別通過synth.speak(msg)和synth.cancel(msg)來播放和取消播放。
          在播放前通過voicesDropdown.selectedOptions[0].value來設置文本的語言(這里如果文本的內(nèi)容語言和播報選擇的語言不一致的話會出現(xiàn)亂讀的情況)。
          最后添加了一個節(jié)流函數(shù),防止多次點擊按鈕不斷播放(最好是能獲取播放的時長,或監(jiān)聽播報完畢事件,這里就是簡單的2秒識別一次,有興趣的小伙伴可以自行編寫)。

          遇到問題

          1、google chrome播放語音可能會卡住,所以無聲音。
          解決方法:在播放語音之前先 調(diào)用一下cancel方法:
          window.speechSynthesis.cancel()
          2、出現(xiàn)警告:speechSynthesis.speak() without user activation is no longer allowed since M71, around December 2018.
          解決方法:進去必須有一個事件動作,如點擊事件click,或者你直接鼠標點擊頁面某處就可以播放了。
          3、SpeechSynthesisUtterance在瀏覽器會存在兼容性問題(如IE不支持),目前主流瀏覽器如Chrome,Edge,Safari等等都是支持的。
          解決方案,提示用戶更換其他瀏覽器訪問,代碼:
          if(!!window.SpeechSynthesisUtterance){ console.log("請使用其他瀏覽器!"}

          瀏覽 52
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  久草久热精品视频 | 成人黄色三级视频 | 久久青娱乐 | 欧美精在线 | 良家 露脸 后入 |