test_mic.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import pyaudio
  2. import wave
  3. mic_index = 1 # 改这里:0 / 1 / None
  4. RATE = 48000 # 改这里
  5. CHUNK = 1024
  6. FORMAT = pyaudio.paInt16
  7. CHANNELS = 1 # 设备1不行再试2
  8. SECONDS = 5
  9. p = pyaudio.PyAudio()
  10. stream = None
  11. try:
  12. print(f"Opening mic index={mic_index}, rate={RATE}, channels={CHANNELS}")
  13. kwargs = {
  14. "format": FORMAT,
  15. "channels": CHANNELS,
  16. "rate": RATE,
  17. "input": True,
  18. "frames_per_buffer": CHUNK,
  19. }
  20. if mic_index is not None:
  21. kwargs["input_device_index"] = mic_index
  22. stream = p.open(**kwargs)
  23. print("recording...")
  24. frames = []
  25. for _ in range(int(RATE / CHUNK * SECONDS)):
  26. data = stream.read(CHUNK, exception_on_overflow=False)
  27. frames.append(data)
  28. print("done")
  29. out_file = f"test_mic_{mic_index}_{RATE}_{CHANNELS}ch.wav"
  30. with wave.open(out_file, "wb") as wf:
  31. wf.setnchannels(CHANNELS)
  32. wf.setsampwidth(p.get_sample_size(FORMAT))
  33. wf.setframerate(RATE)
  34. wf.writeframes(b"".join(frames))
  35. print(f"saved: {out_file}")
  36. except Exception as e:
  37. print("ERROR:", e)
  38. finally:
  39. if stream is not None:
  40. stream.stop_stream()
  41. stream.close()
  42. p.terminate()