使用谷歌Chrome瀏覽器Web Speech API進行文字轉語音轉換


如今,有聲讀物比閱讀書籍更受讀者歡迎,因為他們可以在做任何事情的同時透過收聽獲取知識。此外,一些網站會在每篇文章中新增音訊,因此如果使用者不想閱讀文章,他們可以收聽。

要將普通文字轉換為語音,我們需要使用谷歌Chrome瀏覽器的Web Speech API。在本教程中,我們將學習如何使用谷歌Chrome瀏覽器的Web Speech API將文字轉換為語音。

語法

使用者可以按照以下語法使用谷歌Chrome瀏覽器的Web Speech API進行文字轉語音轉換。

var synth = window.speechSynthesis;
var speechOBj = new SpeechSynthesisUtterance(text);
synth.speak(speechOBj);

在上述語法中,我們初始化了SpeechSynthesisUtterance()物件,並將要朗讀的文字作為引數傳遞。之後,我們使用了speak()方法來朗讀文字。

示例1

下面的示例演示了谷歌Chrome瀏覽器Web Speech API將文字轉換為語音的基本用法。我們使用了HTML的“textarea”標籤來獲取使用者的文字輸入。

在JavaScript中,我們從“textarea”輸入欄位訪問文字。之後,每當使用者點選提交按鈕時,我們使用“textarea”輸入欄位的文字值初始化SpeechSynthesisUtterance的新物件。此外,我們使用speak()方法將文字轉換為語音,使用者可以在輸出中觀察到。

<html>
<body>
   <h3>Text to voice conversion using the Web speech API of Google Chrome</h3>
   <div class = "container">
      <textarea name = "text" id = "text" cols = "30" rows = "10"> Add text to Speak. </textarea>
      <br> <br>
      <button id = "speak"> Speak Text </button>
   </div>
   <script>
      // Writing a javascript code to use web speech api to text to voice conversion
      var synth = window.speechSynthesis;
      var speak = document.getElementById("speak");
      speak.addEventListener("click", () => {
         var text = document.getElementById("text").value;
         var speechOBj = new SpeechSynthesisUtterance(text);
         synth.speak(speechOBj);
      });
   </script>
</body>
</html>

示例2

下面的示例演示了谷歌Chrome瀏覽器Web Speech API的高階用法。在這裡,每當使用者點選按鈕時,它都會呼叫textToVoice()函式,該函式將文字轉換為語音。此外,它還會向語音新增速率和音調值。

此外,setVoices()函式在下拉選單選項中設定所有可用的不同區域的語音。使用者可以選擇下拉選單中的任何語音並更改語音。

接下來,我們添加了恢復、暫停和取消按鈕來執行相應的操作。

<html>
<head>
   <style>
      textarea {
         border: 2px solid green;
         width: 500px;
      }
      .controls {
         margin-top: 10px;
      }
   </style>
</head>
<body>
   <h3>Converting the text to voice using the <i> Web speech API </i> of Google Chrome.</h3>
   <div class = "container">
      <textarea name = "text" id = "text" cols = "30" rows = "10"> Add text to Speak. </textarea>
      <div class = "controls">
      <label for = "voice-select"> Voice </label>
      <select name = "voice" id = "voice-select"> </select>
      <br> <br>
      <label for = "rate-select"> Rate </label>
      <input type = "range" name = "rate" id = "rate-select" min = "0" max = "1" step = "0.1" value = "1">
      <span id = "rate-value"> 10 </span>
      <br> <br>
      <label for = "pitch-select"> Pitch </label>
      <input type = "range" name = "pitch" id = "pitch-select" min = "0" max = "2" step = "0.1" value = "1">
      <span id = "pitch-value"> 10 </span>
      <br> <br>
      <button id = "btn">
         Speak
      </button>
      <button id = "pause"> Pause </button>
      <button id = "resume"> Resume </button>
      <button id = "cancel"> Cancel </button>
   </div>
   <script>
      // Accessing values
      const textarea = document.getElementById('text');
      const voice_select = document.getElementById('voice-select');
      const rateSelect = document.getElementById('rate-select');
      const pitchSelect = document.getElementById('pitch-select');
      const rateval = document.getElementById('rate-value');
      const pitchval = document.getElementById('pitch-value');
      let button = document.getElementById('btn');
      let pause = document.getElementById('pause');
      let resume = document.getElementById('resume');
      let cancel = document.getElementById('cancel');
      
      // Initialize speech API
      const speeachSynth = window.speechSynthesis;
      let AllVoices = [];
      function setVoices() {
         AllVoices = speeachSynth.getVoices();
         var string_op = "";
         AllVoices.forEach(voice => {
            var option = voice.name + ' - ' + voice.lang + ' - ';
            var new_option = "<option data-name='" + voice.name +
            "' data-lang='" + voice.lang + "'>" + option
            + "</option>
"; string_op += new_option; }); voice_select.innerHTML = string_op; } speeachSynth.onvoiceschanged = function () { setVoices(); }; function textToVoice() { if (textarea.value !== '') { // Creating a new speech object const textToSpeak = new SpeechSynthesisUtterance(textarea.value); //If there is an error while speaking, this function textToSpeak.error = e => { console.error('Error occurred...'); }; //Select voice from the dropdown const id = voice_select.selectedIndex; const selectedVoice = voice_select.selectedOptions[0].getAttribute('data-name'); // set voice AllVoices.forEach(voice => { if (voice.name === selectedVoice) { textToSpeak.voice = voice; } }); // select rate and pitch value textToSpeak.rate = rateSelect.value; textToSpeak.pitch = pitchSelect.value; // speak the text speeachSynth.speak(textToSpeak); } }; // update the values of rate and pitch rateSelect.addEventListener('change', event => rateval.innerHTML = (Number.parseFloat(rateSelect.value) * 10) + ""); pitchSelect.addEventListener('change', evt => pitchval.innerHTML = (Number.parseFloat(pitchSelect.value) * 10) + ""); // call the textToVoice function when the button is clicked button.addEventListener('click', e => { e.preventDefault(); textToVoice(); }); // pause the speech pause.addEventListener('click', e => { e.preventDefault(); speeachSynth.pause(); }); // resume the speech resume.addEventListener('click', e => { e.preventDefault(); speeachSynth.resume(); }); // cancel the speech cancel.addEventListener('click', e => { e.preventDefault(); speeachSynth.cancel(); }); </script> </body> </html>

使用者學習瞭如何使用谷歌Chrome瀏覽器的Web Speech API將文字轉換為語音。在第一個示例中,我們看到了Web Speech API的基本用法,在第二個示例中,我們看到了Web Speech API的高階用法。

更新於:2023年4月24日

865 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告