HTML5和JavaScript实现语音合成朗读
作者:互联网
HTML5和JavaScript实现语音合成朗读
先给出效果图,最后给出完整代码
完整代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>H5网页版文字转语音</title>
<style>
article {margin: 0 auto;max-width: 800px;text-align: center;}
textarea {max-width: 600px;width:100%;text-align: left;}
button{border-radius: 3px;border: 1px solid #dddddd;height: 30px;width: 80px;cursor: pointer;}
</style>
</head>
<body>
<article>
<h3 align="center">网页版文字转语音朗读功能:</h3>
<p>
<textarea id="texts" rows="15" class="_play">本网页版本网页版文字转语音朗读支持Microsoft Edge、Google Chrome等浏览器,不必联通网络。</textarea>
</p>
<p>
<label>选择播报语言:</label>
<select id="voiceSelect" οnchange="play()"></select>
</p>
<button class="_search" οnclick="play()">开始</button>
<button οnclick="resume()">继续</button>
<button οnclick="pause()">暂停</button>
<button οnclick="cancel()">清除队列</button>
<button οnclick="cls()">清空</button>
</article>
</body>
<script>
if(!('speechSynthesis' in window)) {
throw alert("对不起,您的浏览器不支持")
}
var _play = document.querySelector("._play"),
to_speak = window.speechSynthesis,
dataName, voiceSelect = document.querySelector("#voiceSelect"),
voices = [];
function play() {
cancel();
to_speak = new SpeechSynthesisUtterance(_play.value);
//to_speak.rate = 1.4;// 设置播放语速,范围:0.1 - 10之间
var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name');
for(i = 0; i < voices.length; i++) {
if(voices[i].name === selectedOption) {
to_speak.voice = voices[i];
}
}
window.speechSynthesis.speak(to_speak);
}
//暂停
function pause() {
window.speechSynthesis.pause();
}
//继续播放
function resume() {
window.speechSynthesis.resume(); //继续
}
//清除所有语音播报创建的队列
function cancel() {
window.speechSynthesis.cancel();
}
//清空文本框
function cls() {
document.getElementById("texts").value=""; 清空文本框
}
//创建选择语言的select标签
function populateVoiceList() {
voices = speechSynthesis.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);
}
}
setTimeout(function() {
populateVoiceList();
}, 0)
</script>
</html>
保存为文件名为 网页版文字转语音朗读.html,用浏览器打开后显示如上图,选择适当的播报语言,再单击“开始”按钮就开始播报了,你可以在文本框中输入要朗读的文字。
标签:function,speechSynthesis,option,JavaScript,voices,window,HTML5,朗读,speak 来源: https://blog.csdn.net/cnds123/article/details/113852216