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
| from pydub import AudioSegment from pydub.playback import play import multiprocessing import wave import numpy as np import scipy import matplotlib.pyplot as plt import matplotlib.animation as animation
music_fn='zaifeixing.wav' times=4
class Scope: def __init__(self,ax,times,fr,frames): self.ax=ax self.times=times self.fr=fr self.frames=frames self.i=0
def paint(self,j): self.ax.cla() n=self.fr//self.times freq_spectra=scipy.fft.fft(self.frames[self.i*n:(self.i+1)*n]) abs_freq=np.abs(freq_spectra) x=np.arange(n//2)*self.fr*2/n x[0]*=2 self.ax.plot(x,abs_freq[:n//2]) self.i+=1
def visualize_freq_spectra(times,fr,frames): fig,ax=plt.subplots() scope=Scope(ax,times,fr,frames) ani=animation.FuncAnimation(fig,scope.paint,interval=1000//times) plt.show()
def play_music(music_fn): song=AudioSegment.from_wav(music_fn) play(song-15)
wav=wave.open(music_fn,'rb') frames=wav.readframes(wav.getnframes()) frames=np.frombuffer(frames,dtype=np.short).reshape((-1,2)).T[0] fr=wav.getframerate() t=multiprocessing.Process(target=visualize_freq_spectra,args=(times,fr,frames)) t.daemon=True # 非阻塞 t.start() play_music(music_fn)
|