Spaces:
Running
Running
import streamlit as st | |
import os | |
import base64 | |
import uuid | |
st.title("Record Audio in Browser") | |
# JavaScript to record audio | |
audio_recorder_js = """ | |
<script> | |
let mediaRecorder; | |
let audioChunks = []; | |
function startRecording() { | |
navigator.mediaDevices.getUserMedia({ audio: true }) | |
.then(stream => { | |
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.readAsDataURL(audioBlob); | |
reader.onloadend = () => { | |
const base64AudioMessage = reader.result.split(',')[1]; | |
fetch('/save_audio', { | |
method: 'POST', | |
body: JSON.stringify({ audio: base64AudioMessage }), | |
headers: { 'Content-Type': 'application/json' } | |
}).then(response => response.json()).then(data => { | |
console.log(data); | |
}); | |
}; | |
}; | |
mediaRecorder.start(); | |
}); | |
} | |
function stopRecording() { | |
mediaRecorder.stop(); | |
} | |
</script> | |
<button onclick="startRecording()">Start Recording</button> | |
<button onclick="stopRecording()">Stop Recording</button> | |
""" | |
st.components.v1.html(audio_recorder_js) | |
# Backend to save audio | |
if "audio_data" not in st.session_state: | |
st.session_state["audio_data"] = None | |
if st.session_state["audio_data"]: | |
audio_bytes = base64.b64decode(st.session_state["audio_data"]) | |
file_name = f"recording_{uuid.uuid4()}.wav" | |
with open(file_name, "wb") as f: | |
f.write(audio_bytes) | |
st.audio(file_name, format="audio/wav") | |
st.success(f"Audio saved as {file_name}") | |