electric-otter commited on
Commit
fc5c959
·
verified ·
1 Parent(s): 66e2d27

Create wavetopic.py

Browse files
Files changed (1) hide show
  1. wavetopic.py +78 -0
wavetopic.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import matplotlib.pyplot as plt
3
+ import sounddevice as sd
4
+ from scipy.fftpack import fft
5
+ import time
6
+ import os
7
+
8
+ # Configuration
9
+ SAMPLE_RATE = 44100 # Hz
10
+ DURATION = 5 # seconds
11
+ CHUNK_SIZE = 1024 # samples
12
+ PLOT_REFRESH_RATE = 0.1 # seconds
13
+
14
+ # Create a figure with two subplots (waveform and spectrum)
15
+ plt.ion() # Interactive mode on
16
+ fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 8))
17
+ fig.suptitle('Live Microphone Waveform & Spectrum')
18
+
19
+ # Initialize empty plots
20
+ line_wave, = ax1.plot(np.arange(CHUNK_SIZE), np.zeros(CHUNK_SIZE))
21
+ line_spectrum, = ax2.plot(np.arange(CHUNK_SIZE//2), np.zeros(CHUNK_SIZE//2))
22
+
23
+ # Axis settings
24
+ ax1.set_ylim(-1, 1)
25
+ ax1.set_xlim(0, CHUNK_SIZE)
26
+ ax1.set_title('Waveform')
27
+ ax1.set_ylabel('Amplitude')
28
+
29
+ ax2.set_xlim(0, CHUNK_SIZE//2)
30
+ ax2.set_ylim(0, 1)
31
+ ax2.set_title('Spectrum')
32
+ ax2.set_ylabel('Magnitude')
33
+ ax2.set_xlabel('Frequency Bin')
34
+
35
+ # Audio callback function
36
+ def audio_callback(indata, frames, time, status):
37
+ if status:
38
+ print(status, flush=True)
39
+
40
+ # Update waveform plot
41
+ line_wave.set_ydata(indata[:, 0])
42
+
43
+ # Compute and update spectrum
44
+ N = len(indata[:, 0])
45
+ yf = fft(indata[:, 0])
46
+ xf = np.linspace(0, SAMPLE_RATE//2, N//2)
47
+ line_spectrum.set_ydata(2/N * np.abs(yf[:N//2]))
48
+
49
+ # Redraw the plots
50
+ fig.canvas.draw()
51
+ fig.canvas.flush_events()
52
+
53
+ # Start streaming
54
+ stream = sd.InputStream(
55
+ callback=audio_callback,
56
+ samplerate=SAMPLE_RATE,
57
+ channels=1,
58
+ blocksize=CHUNK_SIZE
59
+ )
60
+
61
+ try:
62
+ print("Starting audio capture... Press Ctrl+C to stop.")
63
+ with stream:
64
+ while True:
65
+ time.sleep(PLOT_REFRESH_RATE)
66
+ except KeyboardInterrupt:
67
+ print("\nStopping audio capture...")
68
+
69
+ # Save the final plot as an image
70
+ timestamp = time.strftime("%Y%m%d-%H%M%S")
71
+ filename = f"waveform_{timestamp}.png"
72
+ fig.savefig(filename)
73
+ print(f"Saved waveform image as {filename}")
74
+
75
+ plt.close()
76
+ except Exception as e:
77
+ print(f"Error: {e}")
78
+ plt.close()