HTML5 文字转语音

在 HTML5 的标准中曾要求浏览器需要提供语音合成功能,虽然各个浏览器对此特性的支持参差不齐,但值得期待。除了文字转语音 HTML5 的标准中也有提到语音转文字的功能,本文仅讨论前者后者不做赘述,感兴趣的可以自行搜索

HTML 代码

1
2
3
4
5
6
<form action="">
<input type="text" />
<select></select>
<input type="submit" />
</form>
<div class="output"></div>

JavaScript 代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
window.onload = function () {
// 获取浏览器的语音合成属性
var synth = window.speechSynthesis;

var inputForm = document.querySelector('form');
var inputTxt = document.querySelector('input');
var voiceSelect = document.querySelector('select');
var voices = null;

// 获取语音合成属性支持的 Voices 列表
function populateVoiceList() {
// 获取 Voices 列表
voices = synth.getVoices();

for (i = 0; i < voices.length; i++) {
var option = document.createElement('option');
option.textContent = voices[i].name + '【' + voices[i].lang + '】';

if (voices[i].default) {
option.textContent += ' DEFAULT';
}

option.setAttribute('data-lang', voices[i].lang);
option.setAttribute('data-name', voices[i].name);
voiceSelect.appendChild(option);
}
}

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

// 表单提交方法
inputForm.onsubmit = function (event) {
event.preventDefault();

// 实例化语音合成方法
var utterThis = new SpeechSynthesisUtterance(inputTxt.value);
// 获取选中的语音
var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name');
// 匹配选中的语音
for (i = 0; i < voices.length; i++) {
if (voices[i].name === selectedOption) {
utterThis.voice = voices[i];
}
}
// 播放
synth.speak(utterThis);
inputTxt.blur();
}
};

注意

  1. 因为众所周知的原因浏览器中提供的 Goog API 无法使用。
  2. Microsoft API 不稳定,有时候无法播放。
  3. Safari 浏览器中可以使用 Apple API。
  4. 在 Windows 中建议优先使用 Edge 浏览器测试。