Spaces:
Sleeping
Sleeping
import streamlit as st | |
from streamlit_webrtc import webrtc_streamer, WebRtcMode, ClientSettings | |
import av | |
import numpy as np | |
import wave | |
import os | |
st.title("Audio Recorder and Uploader") | |
# Function to save recorded audio | |
def save_audio(frames, filename, sample_width, framerate, nchannels): | |
wf = wave.open(filename, 'wb') | |
wf.setnchannels(nchannels) | |
wf.setsampwidth(sample_width) | |
wf.setframerate(framerate) | |
wf.writeframes(b''.join(frames)) | |
wf.close() | |
# Record audio | |
if st.button("Start Recording"): | |
webrtc_ctx = webrtc_streamer( | |
key="key", | |
mode=WebRtcMode.SENDONLY, | |
client_settings=ClientSettings( | |
rtc_configuration={"iceServers": [{"urls": ["stun:stun.l.google.com:19302"]}]}, | |
media_stream_constraints={"audio": True, "video": False}, | |
), | |
audio_receiver_size=1024, | |
) | |
if webrtc_ctx.audio_receiver: | |
frames = [] | |
sample_width = 2 | |
framerate = 44100 | |
nchannels = 1 | |
while True: | |
try: | |
audio_frames = webrtc_ctx.audio_receiver.get_frames(timeout=1) | |
for frame in audio_frames: | |
sound_chunk = np.frombuffer(frame.to_ndarray(), dtype=np.int16) | |
frames.append(sound_chunk.tobytes()) | |
except av.error.BlockingIOError: | |
break | |
filename = "recorded_audio.wav" | |
save_audio(frames, filename, sample_width, framerate, nchannels) | |
st.audio(filename, format='audio/wav') | |
# Upload audio | |
uploaded_file = st.file_uploader("Upload an audio file", type=["wav", "mp3"]) | |
if uploaded_file is not None: | |
st.audio(uploaded_file, format='audio/wav') | |
file_details = {"filename": uploaded_file.name, "filetype": uploaded_file.type, | |
"filesize": uploaded_file.size} | |
st.write(file_details) | |
with open(os.path.join("uploads", uploaded_file.name), "wb") as f: | |
f.write(uploaded_file.getbuffer()) | |
st.success("File uploaded successfully") | |