You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 06:48:02