<!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">
<title>语音</title>
</head>
<body>请输入您想听的话:<textarea type="text" id="ipt"></textarea><br>
<button id="btn">播放</button>
<script>
const ipt = document.querySelector("#ipt");
const oBtn = document.querySelector("#btn");
const startAudio = () => {
let text = ipt.value
let msg = new SpeechSynthesisUtterance(text);
msg.volume = 2; // 音量
msg.rate = 0.8; // 速度
console.log(msg);
window.speechSynthesis.speak(msg);
}
oBtn.addEventListener("click", () => {
startAudio();
})
ipt.addEventListener("keydown", function (e) {
if (e.code === 'Enter') {
startAudio();
}
})
</script>
</body>
</html>
文字转语音:JS原生api
最新推荐文章于 2024-08-25 09:57:22 发布