问题描述
我已经阅读了很多关于这个主题的不同主题,但似乎仍然无法完成。
对于我在大学的编程课,我必须编写一个程序 (Python) 来分析音频信号(通过麦克风直播)并显示频谱以及时间范围内的信号和电平的离散可视化。
到目前为止,我所拥有的只是一个显示信号随时间变化的程序和一个显示频率的程序,但我试图让它们在一个 GUI 中显示的努力似乎根本不起作用。 如果有人能够对此提供帮助,我们将不胜感激。
随时间变化的信号:
import struct
import numpy as np
import matplotlib.pyplot as plt
import time
#%matplotlib tk
CHUNK = 1024 * 2
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 16000
p = pyaudio.PyAudio()
chosen_device_index = -1
for x in range(0,p.get_device_count()):
info = p.get_device_info_by_index(x)
#print p.get_device_info_by_index(x)
if info["name"] == "pulse":
chosen_device_index = info["index"]
print ("Chosen index: ",chosen_device_index)
stream = p.open(format=FORMAT,channels=CHANNELS,rate=RATE,input_device_index=chosen_device_index,input=True,output=True,frames_per_buffer=CHUNK
)
plt.ion()
fig,ax = plt.subplots()
x = np.arange(0,CHUNK)
data = stream.read(CHUNK)
data_int16 = struct.unpack(str(CHUNK) + 'h',data)
line,= ax.plot(x,data_int16)
#ax.set_xlim([xmin,xmax])
ax.set_ylim([-2**15,(2**15)-1])
while True:
data = struct.unpack(str(CHUNK) + 'h',stream.read(CHUNK))
line.set_ydata(data)
fig.canvas.draw()
fig.canvas.flush_events()
频谱:
import numpy
import math
import matplotlib.pyplot as plt
import matplotlib.animation
RATE = 44100
BUFFER = 882
p = pyaudio.PyAudio()
stream = p.open(
format = pyaudio.paFloat32,channels = 1,rate = RATE,input = True,output = False,frames_per_buffer = BUFFER
)
fig = plt.figure()
line1 = plt.plot([],[])[0]
line2 = plt.plot([],[])[0]
r = range(0,int(RATE/2+1),int(RATE/BUFFER))
l = len(r)
def init_line():
line1.set_data(r,[-1000]*l)
line2.set_data(r,[-1000]*l)
return (line1,line2,)
def update_line(i):
try:
data = numpy.fft.rfft(numpy.fromstring(
stream.read(BUFFER),dtype=numpy.float32)
)
except IOError:
pass
data = numpy.log10(numpy.sqrt(
numpy.real(data)**2+numpy.imag(data)**2) / BUFFER) * 10
line1.set_data(r,data)
line2.set_data(numpy.maximum(line1.get_data(),line2.get_data()))
return (line1,)
plt.xlim(0,RATE/2+1)
plt.ylim(-60,0)
plt.xlabel('Frequency')
plt.ylabel('dB')
plt.title('Spectrometer')
plt.grid()
line_ani = matplotlib.animation.FuncAnimation(
fig,update_line,init_func=init_line,interval=0,blit=True
)
plt.show()
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)