Spaces:
Running
Running
File size: 1,923 Bytes
ebf7fba ecedb67 |
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 |
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}")
|