Contents
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:
"""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 data != '':
stream.write(data)
data = wf.readframes(CHUNK)
# stop stream (4)
stream.stop_stream()
stream.close()
# close PyAudio (5)
p.terminate()
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” outlined below.
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)
"""PyAudio Example: Play a wave file (callback version)."""
import pyaudio
import wave
import time
import sys
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()
# define callback (2)
def callback(in_data, frame_count, time_info, status):
data = wf.readframes(frame_count)
return (data, pyaudio.paContinue)
# open stream using callback (3)
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
channels=wf.getnchannels(),
rate=wf.getframerate(),
output=True,
stream_callback=callback)
# start the stream (4)
stream.start_stream()
# wait for stream to finish (5)
while stream.is_active():
time.sleep(0.1)
# stop stream (6)
stream.stop_stream()
stream.close()
wf.close()
# close PyAudio (7)
p.terminate()
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).
Returns a PortAudio format constant for the specified width.
Parameters: |
|
---|---|
Raises ValueError: | |
when invalid width |
|
Return type: | A PortAudio Sample Format constant |
Returns portaudio version.
Return type: | string |
---|
Returns PortAudio version as a text string.
Return type: | string |
---|
Returns the size (in bytes) for the specified sample format.
Parameters: | format – A PortAudio Sample Format constant. |
---|---|
Raises ValueError: | |
on invalid specified format. | |
Return type: | integer |
Open Audio Library
Advanced Linux Sound Architecture (Linux only)
Steinberg Audio Stream Input/Output
An error ocurred, stop playback/recording
BeOS Sound System
This was the last block of audio data
There is more audio data to come
CoreAudio (OSX only)
a custom data format
DirectSound (Windows only)
32 bit float
Still in development
Buffer overflow in input
Buffer underflow in input
16 bit int
24 bit int
32 bit int
8 bit int
JACK Audio Connection Kit
Multimedia Extension (Windows only)
Not actually an audio device
Open Sound System (Linux only)
Buffer overflow in output
Buffer underflow in output
Just priming, not playing yet
SoundManager (OSX only)
8 bit unsigned int
Windows Vista Audio stack architecture
Windows Driver Model (Windows only)
Use this class to open and close streams.
Details
Initialize PortAudio.
Close a stream. Typically use Stream.close() instead.
Parameters: | stream – An instance of the Stream object. |
---|---|
Raises ValueError: | |
if stream does not exist. |
Return a dictionary containing the default Host API parameters. The keys of the dictionary mirror the data fields of PortAudio’s PaHostApiInfo structure.
Raises IOError: | if no default input device is available |
---|---|
Return type: | dict |
Return the default input Device parameters as a dictionary. The keys of the dictionary mirror the data fields of PortAudio’s PaDeviceInfo structure.
Raises IOError: | No default input device available. |
---|---|
Return type: | dict |
Return the default output Device parameters as a dictionary. The keys of the dictionary mirror the data fields of PortAudio’s PaDeviceInfo structure.
Raises IOError: | No default output device available. |
---|---|
Return type: | dict |
Return the number of PortAudio Host APIs.
Return type: | integer |
---|
Return a dictionary containing the Device parameters for a given Host API’s n’th device. The keys of the dictionary mirror the data fields of PortAudio’s PaDeviceInfo structure.
Parameters: |
|
---|---|
Raises IOError: | for invalid indices |
Return type: | dict |
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.
Parameters: | device_index – The device index |
---|---|
Raises IOError: | Invalid device_index. |
Return type: | dict |
Returns a PortAudio format constant for the specified width.
Parameters: |
|
---|---|
Raises ValueError: | |
for invalid width |
|
Return type: | A PortAudio Sample Format constant. |
Return the number of available PortAudio Host APIs.
Return type: | integer |
---|
Return a dictionary containing the Host API parameters for the host API specified by the host_api_index. The keys of the dictionary mirror the data fields of PortAudio’s PaHostApiInfo structure.
Parameters: | host_api_index – The host api index |
---|---|
Raises IOError: | for invalid host_api_index |
Return type: | dict |
Return a dictionary containing the Host API parameters for the host API specified by the host_api_type. The keys of the dictionary mirror the data fields of PortAudio’s PaHostApiInfo structure.
Parameters: | host_api_type – The desired PortAudio Host API |
---|---|
Raises IOError: | for invalid host_api_type |
Return type: | dict |
Returns the size (in bytes) for the specified sample format (a PortAudio Sample Format constant).
Parameters: | format – A PortAudio Sample Format constant. |
---|---|
Raises ValueError: | |
Invalid specified format. | |
Return type: | integer |
Check to see if specified device configuration is supported. Returns True if the configuration is supported; throws a ValueError exception otherwise.
Parameters: |
|
---|---|
Return type: | bool |
Raises ValueError: | |
tuple containing (error string, PortAudio Error Code). |
Open a new stream. See constructor for Stream.__init__() for parameter details.
Returns: | A new Stream |
---|
Terminate PortAudio.
Attention : | Be sure to call this method for every instance of this object to release PortAudio resources. |
---|
PortAudio Stream Wrapper. Use PyAudio.open() to make a new Stream.
Initialize a stream; this should be called by PyAudio.open(). A stream can either be input, output, or both.
Parameters: |
|
---|---|
Raises ValueError: | |
Neither input nor output are set True. |
Close the stream
Return the CPU load. This is always 0.0 for the blocking API.
Return type: | float |
---|
Return the input latency.
Return type: | float |
---|
Return the input latency.
Return type: | float |
---|
Return the number of frames that can be read without waiting.
Return type: | integer |
---|
Return stream time.
Return type: | float |
---|
Return the number of frames that can be written without waiting.
Return type: | integer |
---|
Returns whether the stream is active.
Return type: | bool |
---|
Returns whether the stream is stopped.
Return type: | bool |
---|
Read samples from the stream. Do not call when using non-blocking mode.
Parameters: | num_frames – The number of frames to read. |
---|---|
Raises IOError: | if stream is not an input stream or if the read operation was unsuccessful. |
Return type: | string |
Start the stream.
Stop the stream. Once the stream is stopped, one may not call write or read. Call start_stream() to resume the stream.
Write samples to the stream. Do not call when using non-blocking mode.
Parameters: |
|
---|---|
Raises IOError: | if the stream is not an output stream or if the write operation was unsuccessful. |
Return type: | None |