Recipe 9.3
Getting the Available Voices
Demo
Available Voices
Name | Language | Default? |
---|
Code
JavaScript
const voices = document.querySelector('#voices tbody');
function renderVoices() {
voices.innerHTML = '';
speechSynthesis.getVoices().forEach(voice => {
const row = document.createElement('tr');
const name = document.createElement('td');
name.textContent = voice.name;
row.append(name);
const language = document.createElement('td');
language.textContent = voice.lang;
row.append(language);
const isDefault = document.createElement('td');
if (voice.default) {
isDefault.innerHTML = '<i class="bi bi-check-circle-fill"></i>';
}
row.append(isDefault);
voices.appendChild(row);
});
}
speechSynthesis.addEventListener('voiceschanged', () => renderVoices());
renderVoices();
HTML
<style>
#container {
max-height: 20rem;
overflow: auto;
}
#container thead th {
position: sticky;
top: 0;
}
</style>
<h3>Available Voices</h3>
<div id="container">
<table id="voices" class="table">
<thead>
<tr>
<th>Name</th>
<th>Language</th>
<th>Default?</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>