在 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 ; function populateVoiceList ( ) { 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(); } };
注意
因为众所周知的原因浏览器中提供的 Goog API 无法使用。
Microsoft API 不稳定,有时候无法播放。
Safari 浏览器中可以使用 Apple API。
在 Windows 中建议优先使用 Edge 浏览器测试。