File size: 2,058 Bytes
ccabf63
4eea44f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
63
64
65
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 и JavaScript для записи аудио
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>
"""

# Streamlit интерфейс
st.title("Audio Recorder")

# Встроенный HTML для записи
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}")