4

I'm trying to select a device to use when I go to record using the PyAudio library in Python but I don't know how to do so. I found this code online that shows all the available input devices:

import pyaudio
p = pyaudio.PyAudio()
info = p.get_host_api_info_by_index(0)
numdevices = info.get('deviceCount')
for i in range(0, numdevices):
        if (p.get_device_info_by_host_api_device_index(0, i).get('maxInputChannels')) > 0:
            print("Input Device id ", i, " - ", p.get_device_info_by_host_api_device_index(0, i))

This works however, how do I select a device to use from this list? I can't seem to find anywhere online about selecting a device to use so if anyone could help me out that would be great, thanks.

3
  • Isn't that explained in a comment here, which is presumably where you got the code? Commented Feb 27, 2020 at 17:31
  • oh ok thank you I didn't see that Commented Feb 27, 2020 at 18:00
  • Does this answer your question? How to select a specific input device with PyAudio Commented Feb 27, 2020 at 18:05

1 Answer 1

3

After you have listed the devices out (by printing them as you have shown in the code from the question) you can choose which index of the devices you want to use.

i.e. it may print out

('Input Device id ', 2, ' - ', u'USB Sound Device: Audio (hw:1,0)')
('Input Device id ', 3, ' - ', u'sysdefault')
('Input Device id ', 11, ' - ', u'spdif')
('Input Device id ', 12, ' - ', u'default')

And then to start recording from that specific device, you need to open a PyAudio stream:

# Open stream with the index of the chosen device you selected from your initial code
stream = p.open(format=p.get_format_from_width(width=2),
                channels=1,
                output=True,
                rate=OUTPUT_SAMPLE_RATE,
                input_device_index=INDEX_OF_CHOSEN_INPUT_DEVICE, # This is where you specify which input device to use
                stream_callback=callback)

# Start processing and do whatever else...
stream.start_stream()

For more information regarding the stream options, take a look at the config specified on PyAudio's official documentation.

If you need help with more of the script I recommend looking at the simple example for non-blocking audio with PyAudio, available on their documentation.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.