前言
看到很多UP主的桌面上都摆上了响度显示摆件,就想着自己动手做一个,刚好手头有不用的Maix Dock K210开发板。因为K210带有FFT所以可以直接做一个频谱显示摆件。
代码
根据官方教程的代码进行了一波魔改:
from Maix import GPIO, I2S, FFT
import image, lcd, math, random, time
from fpioa_manager import fm
#参数设置
sample_rate = 30000
sample_points = 1024
fft_points = 64
#LCD条形柱显示宽度和数量计算
hist_x_num = int(fft_points/2)
hist_width = int(320 / hist_x_num) #changeable
#LCD初始化
lcd.init()
lcd.rotation(0)
lcd.mirror(0)
#麦克风初始化
fm.register(20,fm.fpioa.I2S0_IN_D0, force=True)
fm.register(30,fm.fpioa.I2S0_WS, force=True) # 19 on Go Board and Bit(new version)
fm.register(32,fm.fpioa.I2S0_SCLK, force=True) # 18 on Go Board and Bit(new version)
rx = I2S(I2S.DEVICE_0)
rx.channel_config(rx.CHANNEL_0, rx.RECEIVER, align_mode = I2S.STANDARD_MODE)
rx.set_sample_rate(sample_rate)
#img初始化
img = image.Image()
#增益倍数初始化
times=3.0
while 1:
#FFT计算
audio = rx.record(sample_points)
fft_res = FFT.run(audio.to_bytes(),fft_points)
fft_amp = FFT.amplitude(fft_res)
#绘制幅值
img = img.clear()
x_shift = 0
maxFlag=0
minFlag=0
for i in range(hist_x_num):
amp=int(fft_amp[i]*times)
if amp < 10:
minFlag+=1
elif amp > 230:
maxFlag+=1
#限制振幅
if amp > 240:
hist_height = 240
else:
hist_height = amp
#计算要显示的图像,矩形实心显示。
r=random.randint(0, 255)
g=random.randint(0, 255)
b=random.randint(0, 255)
#img = img.draw_rectangle((x_shift,0,hist_width-1,hist_height),[r,g,b],2,True)
img = img.draw_rectangle((x_shift,120-int(hist_height/2),hist_width-1,hist_height),[r,g,b],2,True)
x_shift = x_shift + hist_width
#显示
#img.draw_string(2,2, str(times), color=(255,255,255), scale=2)
lcd.display(img)
#自适应幅度增益
if maxFlag>0 and minFlag<3:
times-=0.5
elif minFlag>20 and maxFlag<1:
times+=0.2
if times<1:
times=1
elif times>10:
times=10
time.sleep_ms(20)
步骤
将代码复制到MaixPy IDE中运行即可。