Window: thuộc tính speechSynthesis
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 chỉ đọc speechSynthesis của đối tượng Window trả về một đối tượng SpeechSynthesis, đây là điểm vào để dùng chức năng tổng hợp giọng nói của Web Speech API.
Giá trị
Một đối tượng SpeechSynthesis.
Ví dụ
Trong Speech synthesizer demo cơ bản của chúng ta, trước tiên chúng ta lấy tham chiếu tới bộ điều khiển SpeechSynthesis bằng window.speechSynthesis.
Sau khi định nghĩa một số biến cần thiết, chúng ta lấy danh sách các voice có sẵn bằng SpeechSynthesis.getVoices() và điền vào một menu chọn để người dùng có thể chọn voice họ muốn.
Bên trong trình xử lý inputForm.onsubmit, chúng ta chặn việc gửi form bằng preventDefault(), tạo một thể hiện SpeechSynthesisUtterance mới chứa văn bản từ <input>, đặt voice của utterance thành voice được chọn trong phần tử <select>, và bắt đầu phát utterance qua phương thức SpeechSynthesis.speak().
const synth = window.speechSynthesis;
const inputForm = document.querySelector("form");
const inputTxt = document.querySelector("input");
const voiceSelect = document.querySelector("select");
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");
utterThis.voice = voices.find((v) => v.name === selectedOption);
synth.speak(utterThis);
inputTxt.blur();
};
Đặc tả kỹ thuật
| Specification |
|---|
| Web Speech API> # tts-section> |