2

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.

PetSven
  • 366
  • 3
  • 13

2 Answers2

3

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)
PetSven
  • 366
  • 3
  • 13
  • 1
    BTW, you can find the default sampling rate like this: `sounddevice.query_devices(20)['default_samplerate']` – Matthias Aug 13 '19 at 10:17
  • Now I get `Error starting stream: Unanticipated host error [PaErrorCode -9999]: 'WdmSyncIoctl: DeviceIoControl GLE = 0x00000490 (<...>)' [Windows WDM-KS error 0]` – Winand Jun 27 '21 at 23:04
0

You may also need to call CoInitialize in the thread where you open audio stream using WASAPI or WDM-KS (kernel streaming)

ctypes.windll.ole32.CoInitialize(None)

Otherwise I get the following error:

Error starting stream: Unanticipated host error [PaErrorCode -9999]: 'WdmSyncIoctl: DeviceIoControl GLE = 0x00000490 (prop_set = {8C134960-51AD-11CF-878A-94F801C10000}, prop_id = 10)' [Windows WDM-KS error 0]

Then I checked Winapi calls using Rohitab Api Monitor and found that CoMarshalInterThreadInterfaceInStream(IAudioClient2, ...) gives CO_E_NOTINITIALIZED error: enter image description here

Winand
  • 2,093
  • 3
  • 28
  • 48