demo.html
<!DOCTYPE html>
<html>
<head>
<title>文本朗读演示</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 20px auto;
padding: 20px;
}
#textInput {
width: 100%;
height: 150px;
padding: 12px;
margin: 20px 0;
border: 2px solid #007bff;
border-radius: 8px;
font-size: 16px;
}
button {
padding: 12px 24px;
font-size: 16px;
background: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background 0.3s;
}
button:hover {
background: #0056b3;
}
.status {
color: #666;
margin: 10px 0;
font-size: 14px;
}
</style>
</head>
<body>
<h2>文本朗读演示</h2>
<textarea id="textInput" placeholder="请输入要朗读的文本..."></textarea><br>
<button id="speakBtn">开始朗读</button>
<button id="stopBtn">停止朗读</button>
<div class="status" id="status">状态:等待输入</div>
<script>
const synth = window.speechSynthesis;
const speakBtn = document.getElementById('speakBtn');
const stopBtn = document.getElementById('stopBtn');
const statusDiv = document.getElementById('status');
const textInput = document.getElementById('textInput');
// 语音合成初始化
let voices = [];
function loadVoices() {
voices = synth.getVoices();
if (!voices.length) {
statusDiv.textContent = '状态:语音引擎加载中...';
setTimeout(loadVoices, 100);
return;
}
statusDiv.textContent = '状态:准备就绪';
}
// 兼容性检测
if (!synth) {
statusDiv.textContent = '状态:您的浏览器不支持语音合成';
speakBtn.disabled = true;
stopBtn.disabled = true;
} else {
loadVoices();
synth.onvoiceschanged = loadVoices;
}
// 朗读控制
speakBtn.addEventListener('click', () => {
const text = textInput.value.trim();
if (!text) {
alert('请输入要朗读的内容');
return;
}
// 创建语音实例
const utterance = new SpeechSynthesisUtterance(text);
utterance.voice = voices.find(v => v.lang === 'zh-CN') || voices[0];
utterance.rate = 1; // 语速 (0.1-10)
utterance.pitch = 1; // 音调 (0-2)
utterance.volume = 1; // 音量 (0-1)
// 事件监听
utterance.onstart = () => {
statusDiv.textContent = '状态:正在朗读...';
speakBtn.disabled = true;
stopBtn.disabled = false;
};
utterance.onend = () => {
statusDiv.textContent = '状态:朗读完成';
speakBtn.disabled = false;
stopBtn.disabled = true;
};
synth.speak(utterance);
});
// 停止朗读
stopBtn.addEventListener('click', () => {
synth.cancel();
statusDiv.textContent = '状态:已停止';
speakBtn.disabled = false;
stopBtn.disabled = true;
});
</script>
</body>
</html>