83 lines
2.6 KiB
HTML
83 lines
2.6 KiB
HTML
|
|
<!DOCTYPE html>
|
||
|
|
<html lang="en">
|
||
|
|
<head>
|
||
|
|
<meta charset="UTF-8">
|
||
|
|
<title>Real-time Speech Recognition</title>
|
||
|
|
</head>
|
||
|
|
<body>
|
||
|
|
<button id="start">Start Recording</button>
|
||
|
|
<button id="stop" disabled>Stop Recording</button>
|
||
|
|
<div id="output"></div>
|
||
|
|
|
||
|
|
<script>
|
||
|
|
const startButton = document.getElementById('start');
|
||
|
|
const stopButton = document.getElementById('stop');
|
||
|
|
const outputDiv = document.getElementById('output');
|
||
|
|
let mediaRecorder;
|
||
|
|
let socket;
|
||
|
|
|
||
|
|
// 初始化 WebSocket
|
||
|
|
function initWebSocket() {
|
||
|
|
socket = new WebSocket('ws://127.0.0.1:8080/speech-recognition'); // 确保端口正确
|
||
|
|
|
||
|
|
socket.onopen = () => {
|
||
|
|
console.log('WebSocket connection established');
|
||
|
|
startButton.disabled = false;
|
||
|
|
};
|
||
|
|
|
||
|
|
socket.onmessage = (event) => {
|
||
|
|
const result = JSON.parse(event.data);
|
||
|
|
outputDiv.innerHTML += `<p>${result.text}</p>`;
|
||
|
|
};
|
||
|
|
|
||
|
|
socket.onclose = () => {
|
||
|
|
console.log('WebSocket connection closed');
|
||
|
|
// 尝试重连
|
||
|
|
setTimeout(() => {
|
||
|
|
console.log('Reconnecting WebSocket...');
|
||
|
|
initWebSocket();
|
||
|
|
}, 3000); // 3 秒后重连
|
||
|
|
};
|
||
|
|
|
||
|
|
socket.onerror = (error) => {
|
||
|
|
console.error('WebSocket error:', error);
|
||
|
|
};
|
||
|
|
}
|
||
|
|
|
||
|
|
// 开始录音
|
||
|
|
startButton.addEventListener('click', async () => {
|
||
|
|
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
||
|
|
mediaRecorder = new MediaRecorder(stream, { mimeType: 'audio/webm; codecs=opus' }); // 使用 Opus 编码
|
||
|
|
|
||
|
|
mediaRecorder.ondataavailable = (event) => {
|
||
|
|
if (event.data.size > 0) {
|
||
|
|
const reader = new FileReader();
|
||
|
|
reader.onload = () => {
|
||
|
|
if (socket.readyState === WebSocket.OPEN) { // 检查 WebSocket 状态
|
||
|
|
const audioData = reader.result;
|
||
|
|
socket.send(audioData); // 发送音频数据
|
||
|
|
} else {
|
||
|
|
console.error('WebSocket is not open. Current state:', socket.readyState);
|
||
|
|
}
|
||
|
|
};
|
||
|
|
reader.readAsArrayBuffer(event.data);
|
||
|
|
}
|
||
|
|
};
|
||
|
|
|
||
|
|
mediaRecorder.start(1000); // 每 1 秒发送一次数据
|
||
|
|
startButton.disabled = true;
|
||
|
|
stopButton.disabled = false;
|
||
|
|
});
|
||
|
|
|
||
|
|
// 停止录音
|
||
|
|
stopButton.addEventListener('click', () => {
|
||
|
|
mediaRecorder.stop();
|
||
|
|
startButton.disabled = false;
|
||
|
|
stopButton.disabled = true;
|
||
|
|
});
|
||
|
|
|
||
|
|
// 初始化 WebSocket
|
||
|
|
initWebSocket();
|
||
|
|
</script>
|
||
|
|
</body>
|
||
|
|
</html>
|