40_soundLoudnessAnalysis.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #!/usr/bin/env python
  2. #version : 2024.03.07
  3. #language : en
  4. import pyaudio
  5. import numpy as np
  6. from maix import camera, image, display
  7. import time
  8. def waterFallShow(inputVal):
  9. global intensity_recorder,intensity_show,img
  10. if(len(intensity_recorder)<40):
  11. intensity_recorder.append(inputVal)
  12. else:
  13. for i in range(0,39):
  14. intensity_recorder[i]=intensity_recorder[i+1]
  15. intensity_recorder[39]=inputVal
  16. for i in range(0,len(intensity_recorder)):
  17. height=int(intensity_recorder[i])
  18. intensity_show[i] = image.new(size=(7, height), color=(40, 144, 152), mode="RGB")
  19. img.draw_image(intensity_show[i], i*8, 240-height)
  20. image.load_freetype("/root/preset/fonts/CascadiaCodePL-Italic.ttf")
  21. CHUNK = 1024
  22. FORMAT = pyaudio.paInt16
  23. CHANNELS = 1
  24. RATE = 44100
  25. p = pyaudio.PyAudio()
  26. img = image.new(size=(320, 240), color=(0, 0, 0), mode="RGB") # 创建一张红色背景图
  27. stream = p.open(format=FORMAT,
  28. channels=CHANNELS,
  29. rate=RATE,
  30. input=True,
  31. frames_per_buffer=CHUNK)
  32. intensity_recorder = []
  33. intensity_show = [0]*40
  34. print(len(intensity_show))
  35. # 循环读取音频数据
  36. while True:
  37. stream.start_stream()
  38. str_data = stream.read(CHUNK) # 从麦克风获取一帧音频数据
  39. stream.stop_stream()
  40. # 将音频数据转换为NumPy数组
  41. arr = np.frombuffer(str_data, dtype=np.int16)
  42. # 计算音频数据的绝对值之和,即为声音强度
  43. # 1024个16位的wav采样点(-32768~32767)的绝对值之和,需要将其映射到0~1023
  44. intensity = int(np.abs(arr).sum()/32768)
  45. #print(intensity)
  46. img.clear()
  47. waterFallShow(intensity)
  48. img.draw_string(140, 20, "Loudness of sound:"+str(intensity), scale=1.0,color=(255, 255, 255), thickness=1)
  49. display.show(img)
  50. print("main_thread_time:", time.time())
  51. # 关闭流和PyAudio对象
  52. stream.stop_stream()
  53. stream.close()
  54. p.terminate()