|
import streamlit as st |
|
import numpy as np |
|
import soundfile as sf |
|
import tempfile |
|
|
|
|
|
def save_audio_file(audio_bytes): |
|
with tempfile.NamedTemporaryFile(delete=False, suffix='.wav') as tmp_file: |
|
tmp_file.write(audio_bytes) |
|
return tmp_file.name |
|
|
|
|
|
html_code = """ |
|
<script> |
|
let mediaRecorder; |
|
let audioChunks = []; |
|
|
|
function startRecording() { |
|
navigator.mediaDevices.getUserMedia({ audio: true }).then(stream => { |
|
mediaRecorder = new MediaRecorder(stream); |
|
mediaRecorder.start(); |
|
|
|
mediaRecorder.ondataavailable = event => { |
|
audioChunks.push(event.data); |
|
}; |
|
|
|
mediaRecorder.onstop = () => { |
|
const audioBlob = new Blob(audioChunks); |
|
const reader = new FileReader(); |
|
reader.onloadend = function() { |
|
const audioData = reader.result.split(',')[1]; // base64 |
|
const audioBytes = new Uint8Array(atob(audioData).split('').map(c => c.charCodeAt(0))); |
|
const xhr = new XMLHttpRequest(); |
|
xhr.open("POST", "/upload", true); |
|
xhr.setRequestHeader("Content-Type", "application/octet-stream"); |
|
xhr.send(audioBlob); |
|
audioChunks = []; |
|
}; |
|
reader.readAsDataURL(audioBlob); |
|
}; |
|
}); |
|
} |
|
|
|
function stopRecording() { |
|
mediaRecorder.stop(); |
|
} |
|
</script> |
|
|
|
<button onclick="startRecording()">Start Recording</button> |
|
<button onclick="stopRecording()">Stop Recording</button> |
|
""" |
|
|
|
|
|
st.title("Audio Recorder") |
|
|
|
|
|
st.markdown(html_code, unsafe_allow_html=True) |
|
|
|
|
|
if st.button("Upload Audio"): |
|
audio_data = st.file_uploader("Upload your audio file", type=["wav", "mp3"]) |
|
if audio_data is not None: |
|
|
|
audio_file_path = save_audio_file(audio_data.read()) |
|
st.success(f"Audio saved at {audio_file_path}") |