Python使用sounddevice模块录音时持续运行,无法按设定时长自动停止
故障根因排查
核心原因
你遇到的无限录音问题是sounddevice库的wait()函数在部分系统环境下的兼容性bug导致:sounddevice底层依赖PortAudio音频框架,在Windows部分版本、Linux PulseAudio默认配置环境下,全局wait()方法无法正确检测录音任务完成状态,会进入永久阻塞状态。
修复方案
你可以按以下优先级尝试修改:
方案1:补充dtype参数 + 替换等待逻辑
直接修改录音相关代码,不使用全局wait(),改用带超时的主动检测逻辑,同时显式指定录音数据类型避免格式不兼容:
from sounddevice import rec, stop from scipy.io.wavfile import write from getpass import getpass from pyAesCrypt import encryptFile from os import remove import time fs = 44100 # Sample rate while True: try: seconds = int(input("Enter how long to record for: ")) if seconds <= 0: print("Must be a positive integer!") continue except ValueError: print("Must be an integer!") else: break # 显式指定dtype为int16,和scipy write的格式要求匹配 myrecording = rec(int(seconds * fs), samplerate=fs, channels=2, dtype='int16') # 替换全局wait(),用超时等待避免无限阻塞,预留2秒缓冲时间 start_time = time.time() while time.time() - start_time < seconds + 2: time.sleep(0.1) # 检测录音时长是否达到要求 if time.time() - start_time >= seconds: break # 强制停止录音流,避免残留进程 stop() write('output.wav', fs, myrecording) password = getpass("Enter password to encrypt file with: ") encryptFile("output.wav", "output.ewf", password) remove("output.wav") print("Saved file as output.ewf")
方案2:修复底层PortAudio依赖
如果方案1仍然无法解决,说明你当前环境的PortAudio版本存在兼容性问题:
- Linux环境执行:
sudo apt install portaudio19-dev重新安装兼容版本的PortAudio后,执行pip install --force-reinstall sounddevice重装库 - Windows环境可以替换Python环境目录下的PortAudio二进制dll文件,选择官方预编译的稳定版本即可。
内容的提问来源于stack exchange,提问作者itsmii
相关产品推荐
相关产品推荐

