Spaces:
Sleeping
Sleeping
<html lang="ja"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>音声録音</title> | |
</head> | |
<body> | |
<h1>音声録音</h1> | |
<button id="start-recording">録音開始</button> | |
<button id="stop-recording" disabled>録音停止</button> | |
<p>録音した音声を送信する準備ができました。</p> | |
<button id="send-to-server" disabled>音声を送信</button> | |
<script> | |
let mediaRecorder; | |
let audioChunks = []; | |
const startRecordingBtn = document.getElementById('start-recording'); | |
const stopRecordingBtn = document.getElementById('stop-recording'); | |
const sendToServerBtn = document.getElementById('send-to-server'); | |
// 音声録音の開始 | |
startRecordingBtn.addEventListener('click', async () => { | |
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' }); | |
const reader = new FileReader(); | |
reader.onloadend = () => { | |
const base64String = reader.result.split(',')[1]; // Base64エンコードされた音声データを取得 | |
sendToServerBtn.disabled = false; | |
sendToServerBtn.addEventListener('click', () => { | |
// 音声をバックエンドに送信 | |
fetch('/upload_audio', { | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/json', | |
}, | |
body: JSON.stringify({ | |
audio_data: base64String, | |
}), | |
}) | |
.then(response => response.json()) | |
.then(data => { | |
alert('音声がバックエンドに送信されました。'); | |
}) | |
.catch(error => { | |
console.error('エラー:', error); | |
}); | |
}); | |
}; | |
reader.readAsDataURL(audioBlob); | |
}; | |
mediaRecorder.start(); | |
startRecordingBtn.disabled = true; | |
stopRecordingBtn.disabled = false; | |
}); | |
// 音声録音の停止 | |
stopRecordingBtn.addEventListener('click', () => { | |
mediaRecorder.stop(); | |
startRecordingBtn.disabled = false; | |
stopRecordingBtn.disabled = true; | |
}); | |
</script> | |
</body> | |
</html> | |