fadzwan commited on
Commit
0ed912d
·
1 Parent(s): 1364a0c

add audio player

Browse files
Files changed (1) hide show
  1. app.py +26 -5
app.py CHANGED
@@ -69,11 +69,29 @@ st.write("Upload an audio file to generate a spectrogram and predict its class u
69
  uploaded_file = st.file_uploader("Choose an audio file", type=["wav", "mp3"])
70
 
71
  if uploaded_file is not None:
72
- # Save the uploaded audio file to a temporary location
73
- with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as temp_audio_file:
74
- temp_audio_file.write(uploaded_file.read())
 
 
 
 
 
 
 
 
 
 
 
75
  temp_audio_path = temp_audio_file.name
76
 
 
 
 
 
 
 
 
77
  # Preprocess the audio into a spectrogram
78
  st.write("Processing audio into a spectrogram...")
79
  spectrogram = preprocess_audio(temp_audio_path)
@@ -102,8 +120,11 @@ if uploaded_file is not None:
102
  else:
103
  st.write("Failed to process the audio file. Please try again with a different file.")
104
 
105
- # Optional: Clean up temporary file
106
- os.remove(temp_audio_path)
 
 
 
107
 
108
 
109
 
 
69
  uploaded_file = st.file_uploader("Choose an audio file", type=["wav", "mp3"])
70
 
71
  if uploaded_file is not None:
72
+ # Read uploaded bytes so we can both play and save to temp for processing
73
+ file_bytes = uploaded_file.read()
74
+
75
+ # Determine a sensible suffix from the uploaded filename (fall back to .wav)
76
+ try:
77
+ ext = os.path.splitext(uploaded_file.name)[1]
78
+ except Exception:
79
+ ext = ".wav"
80
+ if not ext:
81
+ ext = ".wav"
82
+
83
+ # Save the uploaded audio file to a temporary location for librosa processing
84
+ with tempfile.NamedTemporaryFile(delete=False, suffix=ext) as temp_audio_file:
85
+ temp_audio_file.write(file_bytes)
86
  temp_audio_path = temp_audio_file.name
87
 
88
+ # Provide an audio player in Streamlit using the raw bytes
89
+ try:
90
+ st.audio(file_bytes, format=(uploaded_file.type if hasattr(uploaded_file, "type") else None))
91
+ except Exception:
92
+ # Fallback: try to let Streamlit infer format
93
+ st.audio(file_bytes)
94
+
95
  # Preprocess the audio into a spectrogram
96
  st.write("Processing audio into a spectrogram...")
97
  spectrogram = preprocess_audio(temp_audio_path)
 
120
  else:
121
  st.write("Failed to process the audio file. Please try again with a different file.")
122
 
123
+ # Clean up temporary file
124
+ try:
125
+ os.remove(temp_audio_path)
126
+ except Exception:
127
+ pass
128
 
129
 
130