41_soundSpectrumAnalysis.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import pyaudio
  2. import numpy as np
  3. from maix import camera, image, display
  4. import time
  5. CHUNK = 1024
  6. FORMAT = pyaudio.paInt16
  7. CHANNELS = 2
  8. RATE = 44100
  9. p = pyaudio.PyAudio()
  10. img = image.new(size=(320, 240), color=(0, 0, 0), mode="RGB") # 创建一张背景图
  11. stream = p.open(format=FORMAT,
  12. channels=CHANNELS,
  13. rate=RATE,
  14. input=True,
  15. frames_per_buffer=CHUNK)
  16. intensity_recorder = []
  17. intensity_show = [0]*40
  18. print(len(intensity_show))
  19. # 循环读取音频数据
  20. f_t = np.fft.fftfreq(CHUNK, 1 / RATE) # 传入信号长度及采样率,返回对应频率
  21. while True:
  22. stream.start_stream()
  23. str_data = stream.read(CHUNK) # 从麦克风获取一帧音频数据
  24. stream.stop_stream()
  25. print("type str_data:",type(str_data))
  26. print("str_data:",str_data)
  27. # 将音频数据转换为NumPy数组
  28. arr = np.frombuffer(str_data, dtype=np.int16) #在这里用numpy.frombuffer与
  29. #numpy.fromstring效果相同
  30. print("arr:",arr)
  31. print("type arr1:",type(arr))
  32. arr.shape = -1,2
  33. # 将数组转置
  34. arr = arr.T
  35. print("arr2:",arr)
  36. print("3",len(arr[0].tolist()))
  37. f_signal = np.fft.fft(arr[0])
  38. #f_signal=np.abs(f_signal)
  39. #print("ft:",f_t)
  40. #print("ft len:",len(f_t.tolist()))
  41. #print("f_signal:",f_signal)
  42. #print("f_signal len:",len(f_signal.tolist()))
  43. # 取前512个数据,即正频率部分
  44. fft_data = f_signal[:512]
  45. # 将前512个数据分成32组,每组包含16个数据
  46. fft_data = np.split(fft_data, 32)
  47. # 对每组数据进行平均,得到每组的平均幅值
  48. avg_data = np.abs(fft_data).mean(axis=1)
  49. print(avg_data)
  50. img.clear()
  51. for i in range(0,32):
  52. height=int(avg_data.tolist()[i]/500)
  53. intensity_show[i] = image.new(size=(7, height), color=(40, 144, 152), mode="RGB")
  54. img.draw_image(intensity_show[i], i*8, 240-height)
  55. #img.draw_string(30, 20, "intensity"+str(intensity), scale=1.0,color=(255, 255, 255), thickness=1)
  56. display.show(img)
  57. print("main_thread_time:", time.time())
  58. # 关闭流和PyAudio对象
  59. stream.stop_stream()
  60. stream.close()
  61. p.terminate()