PyAudio provides Python bindings for PortAudio v19, the cross-platform audio I/O library. With PyAudio, you can easily use Python to play and record audio on a variety of platforms, such as GNU/Linux, Microsoft Windows, and Apple macOS.
PyAudio is distributed under the MIT License.
This library was originally inspired by:
Also, PyAudio 0.2.14 pre-compiled wheels for Microsoft Windows (32-bit and 64-bit) are now available for Python 3.12 on PyPI. Install using pip, as described below.
pyaudio.Stream
is
now pyaudio.PyAudio.Stream
, which should not affect
existing code, as directly accessing the
module-level pyaudio.Stream
class has always been
unsupported. Use PyAudio.open
instead.
PaMacCoreStreamInfo.get_channel_map()
and PaMacCoreStreamInfo.get_flags()
methods are
deprecated. Use the channel_map
and flags
properties, respectively, instead.
The current version is PyAudio v0.2.14 and supports Python version 3.8+. Install PyAudio using pip on most platforms. For PyAudio versions prior to v0.2.9, PyAudio distributed installation binaries, which are archived here.
Install using pip:
python -m pip install pyaudio
Notes:
Use Homebrew to install the prerequisite portaudio library, then install PyAudio using pip:
brew install portaudio
pip install pyaudio
Notes:
Use the package manager to install PyAudio. For example, on Debian-based systems:
sudo apt-get install python3-pyaudio
If the latest version of PyAudio is not available, install it using pip:
pip install pyaudio
Notes:
portaudio19-dev
) and
the python development package
(e.g., python3-all-dev
) beforehand.
Source is available for download at the Python Package Index (PyPI).
Or clone the git repository:
git clone https://people.csail.mit.edu/hubert/git/pyaudio.git
To build PyAudio from source, you will also need to build PortAudio v19. See the INSTALLATION file in the PyAudio source bundle for build instructions.
Browse the PyAudio API documentation. PyAudio roughly mirrors the PortAudio v19 API 2.0.
The PyAudio source distribution contains a set of demos. Here's a selection from that set:
"""PyAudio Example: Play a wave file."""
import wave
import sys
import pyaudio
CHUNK = 1024
if len(sys.argv) < 2:
print(f'Plays a wave file. Usage: {sys.argv[0]} filename.wav')
sys.exit(-1)
with wave.open(sys.argv[1], 'rb') as wf:
# Instantiate PyAudio and initialize PortAudio system resources (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)
# Play samples from the wave file (3)
while len(data := wf.readframes(CHUNK)): # Requires Python 3.8+ for :=
stream.write(data)
# Close stream (4)
stream.close()
# Release PortAudio system resources (5)
p.terminate()
"""PyAudio Example: Record a few seconds of audio and save to a wave file."""
import wave
import sys
import pyaudio
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1 if sys.platform == 'darwin' else 2
RATE = 44100
RECORD_SECONDS = 5
with wave.open('output.wav', 'wb') as wf:
p = pyaudio.PyAudio()
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True)
print('Recording...')
for _ in range(0, RATE // CHUNK * RECORD_SECONDS):
wf.writeframes(stream.read(CHUNK))
print('Done')
stream.close()
p.terminate()
"""PyAudio Example: full-duplex wire between input and output."""
import sys
import pyaudio
RECORD_SECONDS = 5
CHUNK = 1024
RATE = 44100
p = pyaudio.PyAudio()
stream = p.open(format=p.get_format_from_width(2),
channels=1 if sys.platform == 'darwin' else 2,
rate=RATE,
input=True,
output=True,
frames_per_buffer=CHUNK)
print('* recording')
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
stream.write(stream.read(CHUNK))
print('* done')
stream.close()
p.terminate()
"""PyAudio Example: Play a wave file (callback version)."""
import wave
import time
import sys
import pyaudio
if len(sys.argv) < 2:
print(f'Plays a wave file. Usage: {sys.argv[0]} filename.wav')
sys.exit(-1)
with wave.open(sys.argv[1], 'rb') as wf:
# Define callback for playback (1)
def callback(in_data, frame_count, time_info, status):
data = wf.readframes(frame_count)
# If len(data) is less than requested frame_count, PyAudio automatically
# assumes the stream is finished, and the stream stops.
return (data, pyaudio.paContinue)
# Instantiate PyAudio and initialize PortAudio system resources (2)
p = pyaudio.PyAudio()
# 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)
# Wait for stream to finish (4)
while stream.is_active():
time.sleep(0.1)
# Close the stream (5)
stream.close()
# Release PortAudio system resources (6)
p.terminate()
"""PyAudio Example: Audio wire between input and output. Callback version."""
import time
import sys
import pyaudio
DURATION = 5 # seconds
def callback(in_data, frame_count, time_info, status):
return (in_data, pyaudio.paContinue)
p = pyaudio.PyAudio()
stream = p.open(format=p.get_format_from_width(2),
channels=1 if sys.platform == 'darwin' else 2,
rate=44100,
input=True,
output=True,
stream_callback=callback)
start = time.time()
while stream.is_active() and (time.time() - start) < DURATION:
time.sleep(0.1)
stream.close()
p.terminate()
"""PyAudio Example: macOS-only: Play a wave file with channel maps."""
import wave
import sys
import pyaudio
CHUNK = 1024
if len(sys.argv) < 2:
print(f'Plays a wave file. Usage: {sys.argv[0]} filename.wav')
sys.exit(-1)
# standard L-R stereo
# channel_map = (0, 1)
# reverse: R-L stereo
# channel_map = (1, 0)
# no audio
# channel_map = (-1, -1)
# left channel audio --> left speaker; no right channel
# channel_map = (0, -1)
# right channel audio --> right speaker; no left channel
# channel_map = (-1, 1)
# left channel audio --> right speaker
# channel_map = (-1, 0)
# right channel audio --> left speaker
channel_map = (1, -1)
# etc...
try:
stream_info = pyaudio.PaMacCoreStreamInfo(
flags=pyaudio.PaMacCoreStreamInfo.paMacCorePlayNice,
channel_map=channel_map)
except AttributeError:
print(
'Could not find PaMacCoreStreamInfo. Ensure you are running on macOS.')
sys.exit(-1)
print('Stream Info Flags:', stream_info.flags)
print('Stream Info Channel Map:', stream_info.channel_map)
with wave.open(sys.argv[1], 'rb') as wf:
p = pyaudio.PyAudio()
stream = p.open(
format=p.get_format_from_width(wf.getsampwidth()),
channels=wf.getnchannels(),
rate=wf.getframerate(),
output=True,
output_host_api_specific_stream_info=stream_info)
# Play stream
while len(data := wf.readframes(CHUNK)): # Requires Python 3.8+ for :=
stream.write(data)
stream.close()
p.terminate()
Copyright (c) 2006 Hubert Pham
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Many thanks to Andrew Baldwin, Alex ThreeD, Timothée Lecomte, Frank Samuelson, Matthieu Brucher, Chris Stawarz, Barry Walker, Bob Jamison, Danilo J. S. Bellini, Bastian Bechtold, Christoph Gohlke, Sebastian Audet, Jason Roehm, Tony Jacobson, Sami Liedes, Michael Graczyk, Blaise Potard, Matthias Schaff, Timothy Port, Sean Zimmermann, Jason Hihn, Eiichi Takamori, Matěj Cepl, Vasily Zakharov, Artur Janowiec, and Bhanu Victor DiCara for their much appreciated suggestions and patches—as well as to others who have written to say hello!
Special thanks to Felipe Sateler and Justin Mazzola Paluska for Debian/Ubuntu packaging help.
The development of PyAudio was funded in part by the Cambridge-MIT Institute and T-Party.
Comments, suggestions, and patches welcomed. Send mail to my first name at mit.edu.