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

求助:如何实现条件为True时的实时音频录制(当前仅支持固定时长)

解决持续录制音频的方案

你可以通过流式录制替代固定时长的rec函数,利用sounddevice.InputStream实现条件触发的持续录制——核心逻辑是实时捕获音频数据,直到指定条件变为False为止,具体实现如下:

代码示例

import numpy as np
import sys
from sounddevice import InputStream, wait
from scipy.io.wavfile import write

# 录制参数配置
sample_rate = 44100
channels = 2
audio_fragments = []  # 存储实时捕获的音频块

# 自定义停止条件(示例用用户输入控制,可替换为业务逻辑条件)
stop_recording = False

def audio_callback(indata, frames, time, status):
    if status:
        print(status, file=sys.stderr)
    if not stop_recording:
        audio_fragments.append(indata.copy())

# 启动流式录制
with InputStream(samplerate=sample_rate, channels=channels, callback=audio_callback):
    print("录制中,输入q并回车停止...")
    while not stop_recording:
        # 此处替换为你的条件判断逻辑,比如检测变量、外部信号等
        user_input = input().strip()
        if user_input.lower() == 'q':
            stop_recording = True
    wait()

# 拼接音频块并保存为WAV文件
full_audio = np.concatenate(audio_fragments, axis=0)
write('output.wav', sample_rate, full_audio)

关键说明

  • 流式捕获:InputStream会持续从音频设备拉取数据,通过回调函数audio_callback实时存储音频片段,摆脱固定时长限制。
  • 灵活停止条件:示例中用用户输入触发停止,你可以直接替换为任意布尔判断(比如检测程序内部状态、硬件信号等)。
  • 数据拼接:录制过程中收集的是多个小音频块,最后用np.concatenate拼接成完整音频数组,再写入文件。

内容的提问来源于stack exchange,提问作者file

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 06:45:01