SpeechSynthesisUtterance: voice property

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2018.

Thuộc tính voice của giao diện SpeechSynthesisUtterance lấy và đặt giọng nói sẽ được dùng để đọc yêu cầu phát âm.

Giá trị này nên được đặt thành một trong các đối tượng SpeechSynthesisVoice được trả về bởi SpeechSynthesis.getVoices(). Nếu không được đặt khi yêu cầu phát âm bắt đầu, giọng nói mặc định phù hợp nhất có sẵn cho cài đặt lang của yêu cầu phát âm sẽ được sử dụng.

Giá trị

Một đối tượng SpeechSynthesisVoice.

Ví dụ

js
const synth = window.speechSynthesis;

const inputForm = document.querySelector("form");
const inputTxt = document.querySelector("input");
const voiceSelect = document.querySelector("select");

const voices = synth.getVoices();

// …

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;
    }
  }
  synth.speak(utterThis);
  inputTxt.blur();
};

Thông số kỹ thuật

Specification
Web Speech API
# dom-speechsynthesisutterance-voice

Tương thích trình duyệt

Xem thêm