naohiro701 commited on
Commit
647b493
·
verified ·
1 Parent(s): 590bd2e

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -0
app.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import matplotlib.pyplot as plt
3
+ from matplotlib.animation import FuncAnimation
4
+ from pydub import AudioSegment
5
+ from scipy.fftpack import fft
6
+ import streamlit as st
7
+ import tempfile
8
+ import os
9
+
10
+ # Streamlit App
11
+ def main():
12
+ st.title("MP3 Fourier Transform Visualizer")
13
+
14
+ uploaded_file = st.file_uploader("Upload an MP3 file", type=["mp3"])
15
+
16
+ if uploaded_file is not None:
17
+ # Convert MP3 to WAV for easier processing
18
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as temp_mp3:
19
+ temp_mp3.write(uploaded_file.read())
20
+ audio = AudioSegment.from_file(temp_mp3.name)
21
+
22
+ samples = np.array(audio.get_array_of_samples())
23
+ sample_rate = audio.frame_rate
24
+
25
+ # Normalize samples
26
+ if audio.channels == 2:
27
+ samples = samples.reshape((-1, 2))
28
+ samples = samples.mean(axis=1) # Convert to mono
29
+
30
+ # Define FFT parameters
31
+ chunk_size = 2048 # Number of samples per frame
32
+ overlap = 1024 # Overlap between frames
33
+ step_size = chunk_size - overlap
34
+
35
+ # Calculate the FFT for each chunk
36
+ freqs = np.fft.rfftfreq(chunk_size, d=1/sample_rate)
37
+ n_chunks = (len(samples) - chunk_size) // step_size + 1
38
+ fft_frames = []
39
+
40
+ for i in range(n_chunks):
41
+ chunk = samples[i * step_size:i * step_size + chunk_size]
42
+ windowed = chunk * np.hanning(len(chunk))
43
+ spectrum = np.abs(fft(windowed)[:len(freqs)])
44
+ fft_frames.append(spectrum)
45
+
46
+ fft_frames = np.array(fft_frames)
47
+
48
+ # Create animation
49
+ fig, ax = plt.subplots()
50
+ line, = ax.plot(freqs, fft_frames[0])
51
+ ax.set_xlim(0, np.max(freqs))
52
+ ax.set_ylim(0, np.max(fft_frames))
53
+ ax.set_xlabel("Frequency (Hz)")
54
+ ax.set_ylabel("Amplitude")
55
+ ax.set_title("Frequency Spectrum Over Time")
56
+
57
+ def update(frame):
58
+ line.set_ydata(fft_frames[frame])
59
+ return line,
60
+
61
+ ani = FuncAnimation(fig, update, frames=len(fft_frames), blit=True)
62
+
63
+ # Save animation to a temporary file
64
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as temp_video:
65
+ ani.save(temp_video.name, fps=30, extra_args=['-vcodec', 'libx264'])
66
+ video_path = temp_video.name
67
+
68
+ st.video(video_path)
69
+
70
+ # Cleanup temporary files
71
+ os.remove(temp_mp3.name)
72
+ os.remove(video_path)
73
+
74
+ if __name__ == "__main__":
75
+ main()