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

Python录音无输出声音问题求助:文件时长正常但无输入信号

音频录制无声音问题排查

我找到一段用sounddevice+soundfile实现的Python录音代码,录出来的文件时长正常,但播放完全没声音,推测是没获取到输入信号。我怀疑是输入设备选择错误导致的问题?另外我还试了一段基于pyaudio的代码,结果也是一样的。麻烦帮忙看看问题出在哪?

第一段代码(sounddevice+soundfile)

import sounddevice as sd
import soundfile as sf
import threading
import queue


class AudioRecorder:
    def __init__(self):

        self.open = True
        self.file_name = None
        self.channels = 1
        self.q = queue.Queue()

        device_info = sd.query_devices(2, 'input')
        self.samplerate = int(device_info['default_samplerate'])

    def callback(self, indata, frames, time, status):
        self.q.put(indata.copy())

    def record(self):
        with sf.SoundFile(self.file_name, mode='x', samplerate=self.samplerate, channels=self.channels) as file:
            with sd.InputStream(samplerate=self.samplerate, channels=self.channels, callback=self.callback):
                while self.open is True:
                    file.write(self.q.get())

    def stop(self):
        self.open = False

    def start(self, file_name):
        self.open = True
        self.file_name = file_name

        audio_thread = threading.Thread(target=self.record)
        audio_thread.start()


recorder = AudioRecorder()
recorder.start('recording.wav')
input('')
recorder.stop()

第二段代码(pyaudio)

from threading import Thread
import pyaudio
import wave

def record():
    global stream, close, frames
    while True:
        if close: break
        data = stream.read(1024)
        frames.append(data)


audio = pyaudio.PyAudio()
close = False
stream = audio.open(format=pyaudio.paInt16, channels=1, rate=44100, input=True, frames_per_buffer=1024)
frames = []

Thread(target=record).start()
input('')
close = True

stream.stop_stream()
stream.close()
audio.terminate()

sound_file = wave.open("recording.wav", "wb")
sound_file.setnchannels(1)
sound_file.setsampwidth(audio.get_sample_size(pyaudio.paInt16))
sound_file.setframerate(44100)
sound_file.writeframes(b''.join(frames))
sound_file.close()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 19:22:48