PyAudio provides Python bindings for PortAudio, the cross-platform audio I/O library. With PyAudio, you can easily use Python to play and record audio on a variety of platforms. PyAudio is inspired by:
1.pyPortAudio/fastaudio: Python bindings for PortAudio v18 API.
2.tkSnack: cross-platform sound toolkit for Tcl/Tk and Python.
Note: stream_callback is called in a separate thread (from the main thread). Exceptions that occur in the stream_callback will:
1.print a traceback on standard error to aid debugging,
2.queue the exception to be thrown (at some point) in the main thread, and
3.return paAbort to PortAudio to stop the stream.
Note: Do not call Stream.read() or Stream.write() if using non-blocking operation.
See: PortAudio’s callback signature for additional details :
Blocking Mode Audio I/O
"""PyAudio Example: Play a wave file."""
To use PyAudio, first instantiate PyAudio using pyaudio.PyAudio() (1), which sets up the portaudio system.
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.
Play audio by writing audio data to the stream using pyaudio.Stream.write(), or read audio data from the stream using pyaudio.Stream.read(). (3)
Note that in “blocking mode”, each pyaudio.Stream.write() or pyaudio.Stream.read() blocks until all the given/requested frames have been played/recorded. Alternatively, to generate audio data on the fly or immediately process recorded audio data, use the “callback mode”(refer the example on call back mode)
Use pyaudio.Stream.stop_stream() to pause playing/recording, and pyaudio.Stream.close() to terminate the stream. (4)
Finally, terminate the portaudio session using pyaudio.PyAudio.terminate() (5)
Callback Mode Audio I/O
In callback mode, PyAudio will call a specified callback function (2) whenever it needs new audio data (to play) and/or when there is new (recorded) audio data available. Note that PyAudio calls the callback function in a separate thread. The function has the following signature
callback(<input_data>, <frame_count>, <time_info>, <status_flag>) and must return a tuple containing
frame_count frames of audio data and a flag signifying whether there are more frames to play/record.
Start processing the audio stream using pyaudio.Stream.start_stream() (4), which will call the callback function repeatedly until that function returns pyaudio.paComplete.
To keep the stream active, the main thread must not terminate, e.g., by sleeping (5).