How to select a specific input device with PyAudio

Asked
Active3 hr before
Viewed126 times

6 Answers

specificselectinput
90%

When recording audio via PyAudio, how do you specify the exact input device to use?, How to check for a specific string with linebreaks in a file with grep? ,Here is an example code that lists available input and output audio devices.,To find out what that device index is, you can follow the code provided in this Github Gist or by following the code found on the Raspberry Pi Forum which provides an example of the outputted code.

you can use: get_device_info_by_host_api_device_index. For instance:

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).get('name')
load more v
88%

To record or play audio, open a stream on the desired device with the desired audio parameters using pyaudio.PyAudio.open() (2). This sets up a pyaudio.Stream to play or record audio.,Use pyaudio.Stream.stop_stream() to pause playing/recording, and pyaudio.Stream.close() to terminate the stream. (4),Return the Device parameters for device specified in device_index as a dictionary. The keys of the dictionary mirror the data fields of PortAudio’s PaDeviceInfo structure.,Start processing the audio stream using pyaudio.Stream.start_stream() (4), which will call the callback function repeatedly until that function returns pyaudio.paComplete.

""
"PyAudio Example: Play a wave file."
""

import pyaudio
import wave
import sys

CHUNK = 1024

if len(sys.argv) < 2:
   print("Plays a wave file.\n\nUsage: %s filename.wav" % sys.argv[0])
sys.exit(-1)

wf = wave.open(sys.argv[1], 'rb')

# instantiate PyAudio(1)
p = pyaudio.PyAudio()

# open stream(2)
stream = p.open(format = p.get_format_from_width(wf.getsampwidth()),
   channels = wf.getnchannels(),
   rate = wf.getframerate(),
   output = True)

# read data
data = wf.readframes(CHUNK)

# play stream(3)
while len(data) > 0:
   stream.write(data)
data = wf.readframes(CHUNK)

# stop stream(4)
stream.stop_stream()
stream.close()

# close PyAudio(5)
p.terminate()
load more v
72%

Get voice input with microphone in Python using PyAudio and SpeechRecognition,Voice Command Calculator in Python using speech recognition and PyAudio,To work with the microphone or audio input device in your Python program, you have to enter the device name or index to specify which device you want to use.,Now the question arises which device will work properly and how to use these microphones.

The commands are:

pip install SpeechRecognition
pip install pyaudio

For Mac users install the following packages first:

brew install portaudio
pip install pyaudio

Linux Users may use this:

$ sudo apt - get install python - pyaudio python3 - pyaudio

Using the below code we can import the package.

import speech_recognition as s_r

The following line will return all the mic devices attached to your PC.

s_r.Microphone.list_microphone_names()

Print all the mic connected to your machine in Python

import speech_recognition as s_r
print(s_r.Microphone.list_microphone_names()) #print all the microphones connected to your machine

Output:

['Microsoft Sound Mapper - Input', 'Microphone (Realtek High Defini', 'Microsoft Sound Mapper - Output', 'Speaker/HP (Realtek High Defini']
mic = s_r.Microphone(device_index = 1)
load more v
65%

Keep in mind that input and output sections of a single audio device will appear as separate items here. It also applies to different audio interfaces of a physical unit (e.g. analog/digital, line/headphone, optical/coaxial, etc.),Since PyAudio depends on PortAudio you will need to have it installed in order for installation to be successful.,Similarly, you can read audio samples from the input. Create an input stream with parameters corresponding to your input device configuration (check audio system settings to explore that):,Let’s check the details of a default audio output device:

For example, for Python 3.7 choose:

pip install PyAudio‑ 0.2 .11‑ cp37‑ cp37m‑ win_amd64.whl
load more v
75%

If you want to use audio input from microphones, PyAudio is also necessary. If not installed, the library will still work, but Microphone will be undefined.,PyAudio (required only if you need to use microphone input),Creates a new Microphone instance, which represents a physical microphone on the computer. Subclass of AudioSource.,The actual energy threshold you will need depends on your microphone or audio data.

Recognize speech input from the microphone:

                                               # NOTE: this requires PyAudio because it uses the Microphone class
                                               import speech_recognition as sr
                                               r = sr.Recognizer()
                                               with sr.Microphone() as source: # use the
                                               default microphone as the audio source
                                               audio = r.listen(source) # listen
                                               for the first phrase and extract it into audio data

                                               try:
                                               print("You said " + r.recognize(audio)) # recognize speech using Google Speech Recognition
                                               except LookupError: # speech is unintelligible
                                               print("Could not understand audio")

Transcribe a WAV audio file:

import speech_recognition as sr
r = sr.Recognizer()
with sr.WavFile("test.wav") as source: # use "test.wav"
as the audio source
audio = r.record(source) # extract audio data from the file

try:
print("Transcription: " + r.recognize(audio)) # recognize speech using Google Speech Recognition
except LookupError: # speech is unintelligible
print("Could not understand audio")

Transcribe a WAV audio file and show the confidence of each:

import speech_recognition as sr
r = sr.Recognizer()
with sr.WavFile("test.wav") as source: # use "test.wav"
as the audio source
audio = r.record(source) # extract audio data from the file

try:
list = r.recognize(audio, True) # generate a list of possible transcriptions
print("Possible transcriptions:")
for prediction in list:
   print(" " + prediction["text"] + " (" + str(prediction["confidence"] * 100) + "%)")
except LookupError: # speech is unintelligible
print("Could not understand audio")

Listening to a microphone in the background:

import speech_recognition as sr
def callback(recognizer, audio): # this is called from the background thread
try:
print("You said " + recognizer.recognize(audio)) # received audio data, now need to recognize it
except LookupError:
   print("Oops! Didn't catch that")
r = sr.Recognizer()
r.listen_in_background(sr.Microphone(), callback)

import time
while True: time.sleep(0.1) # we 're still listening even though the main thread is blocked
load more v
40%

Check if given input device settings are supported.,Check if given output device settings are supported.,Same as check_input_settings(), just for output device settings.,Information and capabilities of PortAudio devices. Devices may support input, output or both input and output.

python3 - m sounddevice
load more v

Other "specific-select" queries related to "How to select a specific input device with PyAudio"