<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Text to Speech</title>
<style>
#text-to-speak {
transition: height 0.5s ease-in-out, width 0.5s ease-in-out;
/* 添加过渡效果 */
}
body {
background-color: gray;
}
textarea {
position: absolute;
left: 0;
right: 0;
margin: auto;
width: 60vh;
height: 90vh;
background-color: gray;
outline: none;
}
</style>
</head>
<body>
<div>
<textarea id="text-to-speak" rows="4" cols="50">你好,请在此输入文本!</textarea>
<button id="speak-button">开始</button>
<button id="pause-button">暂停</button>
<button id="resume-button">继续</button> <!-- 添加继续按钮 -->
</div>
<script>
function $(str) {
const dom = document.querySelectorAll(str);
return dom.length === 1 ? dom[0] : Array.from(dom);
}
const speakButton = $('#speak-button');
const pauseButton = $('#pause-button');
const resumeButton = $('#resume-button'); // 获取继续按钮
const textToSpeak = $('#text-to-speak');
let startIndex = 0;
const chunkSize = 200;
let synth = window.speechSynthesis;
let paused = false; // 用于判断是否暂停
function speakChunk() {
if (paused) return; // 如果已暂停,不继续朗读
const chunk = textToSpeak.value.substring(startIndex, startIndex + chunkSize);
startIndex += chunkSize;
const utterance = new SpeechSynthesisUtterance(chunk);
utterance.onend = () => {
if (startIndex < textToSpeak.value.length) {
speakChunk();
}
};
synth.speak(utterance);
}
speakButton.addEventListener('click', () => {
if ('speechSynthesis' in window) {
if (synth.speaking) {
synth.cancel();
}
startIndex = 0;
textToSpeak.style.height = '0';
textToSpeak.style.width = '0';
speakChunk();
synth.onvoiceschanged = () => {
synth.onvoiceschanged = null;
textToSpeak.style.height = 'initial';
};
} else {
alert('抱歉,你使用的设备不支持 synthesis API!');
}
});
pauseButton.addEventListener('click', () => {
if (synth.speaking) {
synth.pause();
paused = true; // 设置为已暂停状态
}
});
resumeButton.addEventListener('click', () => {
if (paused) {
synth.resume(); // 恢复播放
paused = false; // 设置为非暂停状态
}
});
</script>
<style>
#text-to-speak {
overflow-y: none;
}
#text-to-speak::-webkit-scrollbar {
display: none;
}
</style>
</body>
</html>
SpeechSynthesisUtterance 语音合成(H5) 尝试
于 2023-08-18 20:38:33 首次发布