借用web库 speechSynthesis技术,实现文字转语音功能:
demo可以直接运行查看!
以下为代码实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>new-logo.png">
<title>文字转语音demo</title>
</script>
</head>
<body class="list-box sm-panel-globle scroller">
<noscript>
<strong>We're sorry but manage-desk doesn't work properly without JavaScript enabled. Please enable it to
continue.</strong>
</noscript>
<button id="play">播放</button>
<button id="handleStop">暂停</button>
</body>
<script>
//引入web自带api
const synth = window.speechSynthesis;
const msg = new SpeechSynthesisUtterance();
let btn = document.getElementById('play')
let stopbtn = document.getElementById('handleStop')
btn.onclick = function () {
handleSpeak('我是web 浏览器自带的文字转语音功能 speechSynthesis 这个技术非常好用') // 传入需要播放的文字
}
stopbtn.onclick = function () {
handleStop()
}
function handleSpeak(text) {
msg.text = text; // 文字内容
msg.lang = "zh-CN"; // 使用的语言:中文
msg.volume = 1; // 声音音量:1
msg.rate = 1; // 语速:1
msg.pitch = 1; // 音高:1
synth.speak(msg); // 播放
}
// 语音停止
function handleStop(e) {
msg.text = e;
msg.lang = "zh-CN";
synth.cancel(msg);
}
</script>
</html>