Skip to content

Commit 69c3b67

Browse files
authored
added chroma feature visualizer
1 parent 6a67da6 commit 69c3b67

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

Chroma-Feature-Visualizer.py

+71
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
import numpy as np
2+
import librosa
3+
import librosa.display
4+
import matplotlib.pyplot as plt
5+
from matplotlib.animation import FuncAnimation
6+
import pyaudio
7+
import threading
8+
9+
FRAME_SIZE = 2048
10+
HOP_SIZE = 512
11+
SR = 22050
12+
BUFFER_SIZE = 10
13+
14+
p = pyaudio.PyAudio()
15+
stream = p.open(format=pyaudio.paFloat32, channels=1, rate=SR, input=True, frames_per_buffer=HOP_SIZE)
16+
17+
# Initialize the plot
18+
fig, ax = plt.subplots()
19+
chroma_data = np.zeros((12, BUFFER_SIZE))
20+
img = ax.imshow(chroma_data, aspect='auto', cmap='inferno', origin='lower')
21+
fig.colorbar(img, ax=ax)
22+
ax.set_title('Chroma Feature Visualizer')
23+
ax.set_xlabel('Time')
24+
ax.set_ylabel('Pitch Class')
25+
26+
is_paused = False
27+
28+
# Function to update the plot
29+
def update(frame):
30+
global chroma_data, is_paused
31+
if not is_paused:
32+
data = np.frombuffer(stream.read(HOP_SIZE), dtype=np.float32)
33+
chroma = librosa.feature.chroma_stft(y=data, sr=SR, n_fft=FRAME_SIZE, hop_length=HOP_SIZE)
34+
chroma_db = librosa.amplitude_to_db(chroma, ref=np.max)
35+
chroma_data = np.roll(chroma_data, -1, axis=1)
36+
chroma_data[:, -1] = np.mean(chroma_db, axis=1)
37+
img.set_data(chroma_data)
38+
return [img]
39+
40+
# Function to toggle pause/resume
41+
def toggle_pause(event):
42+
global is_paused
43+
is_paused = not is_paused
44+
45+
# Adding a button to pause/resume
46+
ax_pause = plt.axes([0.81, 0.01, 0.1, 0.075])
47+
btn_pause = plt.Button(ax_pause, 'Pause/Resume')
48+
btn_pause.on_clicked(toggle_pause)
49+
50+
# Function to adjust color map
51+
def change_colormap(event):
52+
current_cmap = img.get_cmap().name
53+
new_cmap = 'inferno' if current_cmap == 'viridis' else 'viridis'
54+
img.set_cmap(new_cmap)
55+
fig.canvas.draw()
56+
57+
# Adding a button to change color map
58+
ax_colormap = plt.axes([0.61, 0.01, 0.15, 0.075])
59+
btn_colormap = plt.Button(ax_colormap, 'Change Color Map')
60+
btn_colormap.on_clicked(change_colormap)
61+
62+
# Create an animation
63+
ani = FuncAnimation(fig, update, frames=BUFFER_SIZE, blit=True, interval=50)
64+
65+
# Start the plot
66+
plt.show()
67+
68+
# Close the stream when done
69+
stream.stop_stream()
70+
stream.close()
71+
p.terminate()

0 commit comments

Comments
 (0)