Spaces:
Running
Running
File size: 2,664 Bytes
3ead8a3 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
// static/script.js
document.addEventListener('DOMContentLoaded', () => {
const recordButton = document.getElementById('recordButton');
const stopButton = document.getElementById('stopButton');
const statusDiv = document.getElementById('status');
const resultDiv = document.getElementById('result');
let mediaRecorder;
let audioChunks = [];
// --- Bắt đầu ghi âm ---
recordButton.addEventListener('click', async () => {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
mediaRecorder = new MediaRecorder(stream);
mediaRecorder.ondataavailable = event => {
audioChunks.push(event.data);
};
mediaRecorder.onstop = () => {
const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
sendAudioToServer(audioBlob);
audioChunks = [];
};
mediaRecorder.start();
statusDiv.textContent = '🔴 Đang ghi âm...';
recordButton.disabled = true;
stopButton.disabled = false;
} catch (error) {
console.error('Lỗi khi truy cập micro:', error);
statusDiv.textContent = 'Lỗi: Không thể truy cập micro.';
}
});
// --- Dừng ghi âm ---
stopButton.addEventListener('click', () => {
mediaRecorder.stop();
statusDiv.textContent = 'Đang xử lý... Vui lòng chờ.';
recordButton.disabled = false;
stopButton.disabled = true;
});
// --- Gửi audio lên server ---
async function sendAudioToServer(audioBlob) {
const formData = new FormData();
formData.append('audio_file', audioBlob, 'recording.wav');
try {
resultDiv.textContent = '...'; // Reset kết quả
const response = await fetch('/predict', {
method: 'POST',
body: formData,
});
if (response.ok) {
const data = await response.json();
resultDiv.textContent = data.prediction;
statusDiv.textContent = 'Hoàn thành! Sẵn sàng ghi âm lần nữa.';
} else {
const errorData = await response.json();
throw new Error(errorData.error || 'Lỗi không xác định từ server.');
}
} catch (error) {
console.error('Lỗi khi gửi audio:', error);
statusDiv.textContent = 'Đã xảy ra lỗi khi gửi audio.';
resultDiv.textContent = 'Lỗi!';
}
}
});
|