Record speakers output with PyAudio

前端 未结 5 888
离开以前
离开以前 2020-11-28 08:41

I\'m trying to record the output from my computer speakers with PyAudio.
I tried to modify the code example given in the PyAudio documentation, but it doesn\'t work.

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 09:31

    I got to record my speaker output with pyaudio with some configuration and code from pyaudio's documentation.

    Code

    """PyAudio example: Record a few seconds of audio and save to a WAVE file."""
    
    import pyaudio
    import wave
    
    CHUNK = 1024
    FORMAT = pyaudio.paInt16
    CHANNELS = 2
    RATE = 44100
    RECORD_SECONDS = 5
    WAVE_OUTPUT_FILENAME = "output.wav"
    
    p = pyaudio.PyAudio()
    
    stream = p.open(format=FORMAT,
                    channels=CHANNELS,
                    rate=RATE,
                    input=True,
                    frames_per_buffer=CHUNK)
    
    print("* recording")
    
    frames = []
    
    for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
        data = stream.read(CHUNK)
        frames.append(data)
    
    print("* done recording")
    
    stream.stop_stream()
    stream.close()
    p.terminate()
    
    wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
    wf.setnchannels(CHANNELS)
    wf.setsampwidth(p.get_sample_size(FORMAT))
    wf.setframerate(RATE)
    wf.writeframes(b''.join(frames))
    wf.close()
    
    

    Configuration

    First, with pulseaudio running, create a loopback device:

    pacmd load-module module-loopback latency_msec=5
    

    Then set the default (fallback) to this loopback device in pavucontrol:

    Then you can start the script, wait 5 seconds, and you should have an output.wav.

提交回复
热议问题