File size: 2,017 Bytes
745ea5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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")