3v324v23's picture
Add application file
3ead8a3
// 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!';
}
}
});