How to select a specific input device with PyAudio
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')
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) sys.exit(-1) wf = wave.open(sys.argv, '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()
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.
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
['Microsoft Sound Mapper - Input', 'Microphone (Realtek High Defini', 'Microsoft Sound Mapper - Output', 'Speaker/HP (Realtek High Defini']
mic = s_r.Microphone(device_index = 1)
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
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
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
Other "specific-select" queries related to "How to select a specific input device with PyAudio"
- Material UI chip input working weired with Korean charactor
- React & reselect
- Filtering an ag-grid based on selected row in another ag-grid
- Move a specific part of text to next line if it have to
- JSPLUMB: disable nodes drag and drop after a specific user interaction
- How to hide text in input field as you type each character?
- ReactJS onChange function not firing on entering input
- Antd Select is not localized until reload
- React-Table with hooks looses focus on input inside table?
- Can we set a specific route to show insted of an dynamic route in nextjs?
- React native why is my textinput text in the middle?
- Material-UI Core TextField globally set InputLabelProps shrink
- React how to select how much I have scrolled below
- Hidden input does not pass the value to the server
- How to sync the antd multiple select table checkbox state with a select option
- Keep the button focused when click on input: Material-Ui
- Mocking file input in React TestUtils
- MUI Select custom MenuItem not working properly
- Css different style to specific div created by map
- Set focus to dynamically created <input fields - use of ID, ref or name?
- UseSelector returns me undefined
- If we have state for the value attribute in the input box, how can we set the previous value when we hit escape in react?
- React Bootstrap select option not showing
- Extract inputs list (fields) from a pdf file to create an html form in react js
- How to create a DateTime equal to 15 minutes ago?
- Webpage Is Detecting Selenium Webdriver with Chromedriver as a bot
- Java.io.IOException: Cannot run program "python" using Spark in Pycharm (Windows)
- Repeat each item in a list a number of times specified in another list
- Scrapy - how to identify already scraped urls
- Sending data from HTML form to a Python script in Flask
- Apply list of functions on an object in Python
- Cannot import name simplejson - After installing simplejson
- Grab a line's whitespace/indention with Python
- Daemonizing celery
- Difference between python - getmtime() and getctime() in unix system
- How do I clear cache with Python Requests?
- Argsort for a multidimensional ndarray
- Avoid references in PyYAML
- How can I use boto to stream a file out of Amazon S3 to Rackspace Cloudfiles?
- Counting non zero values in each column of a dataframe in python
- Download file from web in Python 3
- TensorFlow, why was python the chosen language?
- Python: Respond to Command Line Prompts
- How can I convert a datetime object to milliseconds since epoch (unix time) in Python?