<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>浏览器语音合成</title> </head> <body> <h3>浏览器语音合成</h3> <div> <select id="langs"></select> </div> <div> <textarea id="textarea" cols="50">Tomorrow will be better</textarea> </div> <div><button id="play">Play</button></div> </body> </html>
// 检查浏览器支持 if ('speechSynthesis' in window) { // 使用计时器异步获取语音包 var langsInterval = setInterval(() => { // 设置语言 var langs = window.speechSynthesis.getVoices(); if (langs.length > 0) { clearInterval(langsInterval); } for (var index = 0; index < langs.length; index++) { var lang = langs[index]; var option = new Option(lang.name + ' - ' + lang.lang, lang.lang); document.getElementById("langs").appendChild(option); } }, 100); document.getElementById("play").onclick = function (e) { var msg = new SpeechSynthesisUtterance(); msg.text = document.getElementById("textarea").value; msg.lang = document.getElementById("langs").value; window.speechSynthesis.speak(msg); }; } else { // Ah man, speech synthesis isn't supported. alert("抱歉浏览器不支持语音合成朗读") }