Skip to content

[Windows] Unable to record system audio (loopback) even with Stereo Mix enabled #13

@AmaniBey

Description

@AmaniBey

I tried to record the sound of the system speakers using PyAudio (internal recording), but even though the Stereo Mix device with Windows enabled, I still couldn't obtain any audio input. The following is my code:

import pyaudio
import wave

# Recording Parameters
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
CHUNK = 1024
RECORD_SECONDS = 10
OUTPUT_FILE = "system_sound_recording.wav"

p = pyaudio.PyAudio()

# Obtain device information
device_count = p.get_device_count()
for i in range(device_count):
    device_info = p.get_device_info_by_index(i)
    if "Stereo Mix" in device_info["name"]:
        print(f" device {i}: {device_info['name']}")
        print(f" Maximum number of input channels: {device_info['maxInputChannels']}")
        print(f" whether input is supported: {device_info['maxInputChannels'] > 0}")

# Try to record using the Stereo Mix device (assuming the device index is 2)
device_index = 2 # Please replace it with the actual Stereo Mix device index

stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK,
input_device_index=device_index)

print(" Start recording..." )
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)

print(" Recording Completed ")

stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open(OUTPUT_FILE, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()

Problem manifestation

The code can correctly identify and list the Stereo Mix device (maxInputChannels > 0).
When the program is running, no exception is thrown, but the generated WAV file is empty (or only has noise).
The system sound can be recorded normally in other software (such as Audacity or OBS) using the same device
It has been confirmed that the Stereo Mix device is enabled in the Windows audio Settings

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions