I'm working on a project where a USB audio card is unplugged and plugged arbitrarily from a computer that will be playing sounds. My software should be playing sound as soon as possible right after the card is plugged in.
In order to detect the USB being connected, I'm using libusb's LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED
and LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT
events, and it works flawlessly. As soon as the device is connected to the USB port, the event is triggered. Same when it's removed.
The problem I'm facing is that there's a time gap between the moment libusb detects the device, and the moment I can actually start working with the device to play sound. I'm using miniaudio to play a sinewave, but the issue is the same using Qt Multimedia, so I'm guessing it has to do with the backend (ALSA).
I've had to place an explicit wait of around 5/6 seconds after the device is detected by libusb to be able to safely open it with miniaudio, but I'd rather not have that magic number right there.
Is there any other way of knowing when the device is ready? I've tried checking udev but it gets activated at the same time as libusb.