SpeechSynthesis

Baseline 已廣泛支援

此功能已成熟,並可在多種裝置和瀏覽器版本上使用。自 2018 年 9 月以來,它已在各種瀏覽器中推出。

SpeechSynthesis 介面是 Web Speech API 的語音服務控制器介面;可以使用它來獲取有關裝置上可用語音合成語音的資訊、開始和暫停語音,以及執行其他命令。

EventTarget SpeechSynthesis

例項屬性

SpeechSynthesis 還繼承了其父介面 EventTarget 的屬性。

SpeechSynthesis.paused 只讀

一個布林值,如果 SpeechSynthesis 物件處於暫停狀態,則返回 true

SpeechSynthesis.pending 只讀

一個布林值,如果語音佇列包含尚未朗讀的語音,則返回 true

SpeechSynthesis.speaking 只讀

一個布林值,如果當前正在朗讀語音(即使 SpeechSynthesis 處於暫停狀態),則返回 true

例項方法

SpeechSynthesis 還繼承了其父介面 EventTarget 的方法。

SpeechSynthesis.cancel()

從語音佇列中移除所有語音。

SpeechSynthesis.getVoices()

返回一個表示當前裝置上所有可用語音的 SpeechSynthesisVoice 物件列表。

SpeechSynthesis.pause()

SpeechSynthesis 物件置於暫停狀態。

SpeechSynthesis.resume()

SpeechSynthesis 物件置於非暫停狀態:如果它已暫停,則恢復它。

SpeechSynthesis.speak()

將一個 utterance 新增到語音佇列中;它將在佇列中排在它之前的任何其他語音朗讀完畢後進行朗讀。

事件

使用 addEventListener() 或透過將事件監聽器分配給此介面的 oneventname 屬性來監聽此事件。

voiceschanged

SpeechSynthesis.getVoices() 方法將返回的 SpeechSynthesisVoice 物件列表發生更改時觸發。也可透過 onvoiceschanged 屬性訪問。

示例

首先,一個示例

js
let utterance = new SpeechSynthesisUtterance("Hello world!");
speechSynthesis.speak(utterance);

現在我們將看一個更全面的示例。在我們的 Speech synthesizer demo 中,我們首先使用 window.speechSynthesis 獲取 SpeechSynthesis 控制器的引用。在定義了一些必要的變數後,我們使用 SpeechSynthesis.getVoices() 獲取可用語音列表,並用它們填充一個 select 選單,以便使用者可以選擇他們想要的語音。

inputForm.onsubmit 處理程式中,我們使用 preventDefault() 阻止表單提交,建立一個包含文字 <input> 中文字的新 SpeechSynthesisUtterance 例項,將語音設定為 <select> 元素中選定的語音,並透過 SpeechSynthesis.speak() 方法開始朗讀該語音。

js
const synth = window.speechSynthesis;

const inputForm = document.querySelector("form");
const inputTxt = document.querySelector(".txt");
const voiceSelect = document.querySelector("select");
const pitch = document.querySelector("#pitch");
const pitchValue = document.querySelector(".pitch-value");
const rate = document.querySelector("#rate");
const rateValue = document.querySelector(".rate-value");

let voices = [];

function populateVoiceList() {
  voices = synth.getVoices();

  for (const voice of voices) {
    const option = document.createElement("option");
    option.textContent = `${voice.name} (${voice.lang})`;

    if (voice.default) {
      option.textContent += " — DEFAULT";
    }

    option.setAttribute("data-lang", voice.lang);
    option.setAttribute("data-name", voice.name);
    voiceSelect.appendChild(option);
  }
}

populateVoiceList();
if (speechSynthesis.onvoiceschanged !== undefined) {
  speechSynthesis.onvoiceschanged = populateVoiceList;
}

inputForm.onsubmit = (event) => {
  event.preventDefault();

  const utterThis = new SpeechSynthesisUtterance(inputTxt.value);
  const selectedOption =
    voiceSelect.selectedOptions[0].getAttribute("data-name");
  for (const voice of voices) {
    if (voice.name === selectedOption) {
      utterThis.voice = voice;
    }
  }
  utterThis.pitch = pitch.value;
  utterThis.rate = rate.value;
  synth.speak(utterThis);

  inputTxt.blur();
};

規範

規範
Web Speech API
# tts-section

瀏覽器相容性

另見