Audio Recording Script not working on WSL2 Ubuntu

Viewed 271

I have the following code on WSL2 with Ubuntu:

import pyaudio,wave

chunk = 1024  # Record in chunks of 1024 samples
sample_format = pyaudio.paInt16  # 16 bits per sample
channels = 2
fs = 44100  # Record at 44100 samples per second
seconds = 3
filename = "output.wav"
p = pyaudio.PyAudio()  # Create an interface to PortAudio

print('Recording')

stream = p.open(format=sample_format,
                channels=channels,
                rate=fs,
                frames_per_buffer=chunk,
                input=True)

frames = []  # Initialize array to store frames
for i in range(0, int(fs / chunk * seconds)):
    data = stream.read(chunk)
    frames.append(data)
stream.stop_stream()
stream.close()
p.terminate()

print('Finished recording')
wf = wave.open(filename, 'wb')
wf.setnchannels(channels)
wf.setsampwidth(p.get_sample_size(sample_format))
wf.setframerate(fs)
wf.writeframes(b''.join(frames))
wf.close()

However, when I run the code, I get bunch of ALSA errors and it seems like WSL2 is not recognizing my microphone:

enter image description here

I am unsure if WSL2 has built in audio support as there aren't many examples of recording audio from a script. How can I fix these errors and make WSL2 record audio from my python script?

1 Answers

WSL2 doesn't have direct access to most hardware devices, so it's no surprise that mic access is failing.

That said, there are some ways to access certain hardware devices through WSL2. One of these is through USB/IP, to share a Windows USB device through to WSL2/Linux.

I've used USB/IP, but never for this particular purpose, so I can't say for sure that it will work, but I expect it to. In theory, you will need a USB microphone installed in Windows and to then share that USB device via USB/IP.

You should be able to access the device through PyAudio with that in place.

Related