pythonwasapipython-sounddevice

Why do I get a "Invalid device" error when recording a device using WASAPI and the sounddevice library?


I am trying to write a script to record USB audio from a 4-channel audio device. I am using Python 3.7 and the "sounddevice" library. Upon being compiled the the code gives me an error.

Using the following code, I found the device number of the device I wanted to record:

 >>>sounddevice.query_devices()

This prints out a list of all the audio devices. The one I want to record is device 20:

20 Microphone (USB Device Audio), Windows WASAPI (4 in, 0 out)

Then I used this code to record from that device:

sounddevice.default.device = 20
myrecording = sounddevice.rec(int(duration*fs), samplerate=fs, channels=4, blocking=True) 

However, I get this error whenever I try to record audio from it:

line 18, in <module>
myrecording = sounddevice.rec(int(duration*fs), samplerate=fs, channels=4, blocking=True)
 sounddevice.PortAudioError: Error opening InputStream: Invalid device [PaErrorCode -9996]

I tested this code on a 2-channel MME device and a 2-channel Windows DirectSound device. It works with both of them. But it will not work with my 4-channel WASAPI device.


Solution

  • I found the answer. The sampling frequency "fs" had to match the default sampling frequency for that device in Windows.

    I went to Control Panel -> Sound Recording -> Right Clicked on Device -> Properties -> Advanced. There I found that the default format was "4 Channel, 16 bit, 48000 HZ (DVD Quality)".

    I changed the value of "fs" from 44100 to 48000 and the code started working.

    fs = 48000
    sounddevice.default.device = 20
    myrecording = sounddevice.rec(int(duration*fs), samplerate=fs, channels=4, blocking=True)