Snakey: Headphones wearing Python

PyAudio

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, such as GNU/Linux, Microsoft Windows, and Apple Mac OS X.

PyAudio is inspired by:

What's new

April 12, 2014

PyAudio 0.2.8 is a new release with bug fixes related to the Python GIL and device name encoding.

Many thanks to Jason Roehm for discovering and patching the threading-related issue!

January 30, 2014

Many thanks to Sebastian Audet, who wrote instructions for building PyAudio using Microsoft Visual Studio!

October 27, 2012

PyAudio 0.2.7 is a new release with:

Thanks again to Bastian Bechtold for his help converting the documentation for use with Sphinx! In addition, thanks to John K. Luebs for the callback fix.

October 14, 2012

PyAudio 0.2.6 is a new release with:

Many thanks to Bastian Bechtold and Bob Jamison for their contributions! Without their patches and Bastian's careful review, this release would still be far away. Also, great thanks to Danilo J. S. Bellini for reporting bugs.

Note: As of this update, PyAudio is compatible with Python 2.6, Python 2.7, and Python 3.2. For Python installations older than 2.6, use PyAudio 0.2.4.

August 22, 2012

This web page has been translated to French—thanks to the efforts of Cyril Danilevski!

More news...

Download

The current version is PyAudio v0.2.8, with binaries and source below. Older versions are also available.

Microsoft Windows
Includes: PortAudio v19 [SVN r1919]
Requirements:
Download:   PyAudio for Python 3.3
md5sum: 72237c6204356aaaa914caede30f52be
PyAudio for Python 3.2
md5sum: ed022cff0058ef22aabd79b21c5fd7b1
PyAudio for Python 2.7
md5sum: 3bb90b71f294d2bcf89f0cdb035c31e7
PyAudio for Python 2.6
md5sum: e1808af2cfc58cfc29b3f1b690dbb602

Apple Mac OS X
Includes: PortAudio v19 [SVN r1919]
Requirements: Intel Mac running Apple Mac OS X 10.7+. For Python 3 support, first install MacPython 3.3.
Download:   PyAudio for Mac OS X
md5sum: 230113914e83f4d770ffd4ac327f47f2

Debian/Ubuntu
To install, download the package and then run:
% dpkg -i python{,3}-pyaudio_0.2.8-1_{i386,amd64}.deb

Download:   PyAudio for Python 2 (i386)
md5sum: 1ed6bcc1db76c6ebd386faf7eafef34e
PyAudio for Python 3 (i386)
md5sum: c3d76c7adf3d4cfb82c7c047760f85d3
PyAudio for Python 2 (amd64)
md5sum: f0fb69d6c8c01023ed244b3b54c48f9e
PyAudio for Python 3 (amd64)
md5sum: 38d3feeb10c19d7cdafb0053972810a6

PyAudio Source
To build PyAudio from source, you will also need to build PortAudio v19. See compilation hints for some instructions on building PyAudio for GNU/Linux, Microsoft Windows (cygwin and Win32), and Apple Mac OS X. To build PyAudio using Microsoft Visual Studio, check out Sebastian Audet's instructions.
Download:   PyAudio tarball
md5sum: 5c93a193224cca0183ec434dc558cff5

Git:

% git clone http://people.csail.mit.edu/hubert/git/pyaudio.git

Documentation

Getting started with PyAudio: by example.

Additionally, you can browse the PyAudio API documentation. PyAudio roughly mirrors the PortAudio v19 API 2.0.

If you're building PyAudio from source, here are compilation hints for building PyAudio on GNU/Linux, Windows (cygwin or Win32), and Mac OS X. To build PyAudio using Microsoft Visual Studio, check out Sebastian Audet's instructions!

Examples

Note that the PyAudio source distribution contains a set of demo scripts. Here's a selection from that set:

"""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')

p = pyaudio.PyAudio()

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

data = wf.readframes(CHUNK)

while data != '':
    stream.write(data)
    data = wf.readframes(CHUNK)

stream.stop_stream()
stream.close()

p.terminate()
"""PyAudio example: Record a few seconds of audio and save to a WAVE file."""

import pyaudio
import wave

CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()

stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)

print("* recording")

frames = []

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)

print("* done recording")

stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
"""
PyAudio Example: Make a wire between input and output (i.e., record a
few samples and play them back immediately).
"""

import pyaudio

CHUNK = 1024
WIDTH = 2
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5

p = pyaudio.PyAudio()

stream = p.open(format=p.get_format_from_width(WIDTH),
                channels=CHANNELS,
                rate=RATE,
                input=True,
                output=True,
                frames_per_buffer=CHUNK)

print("* recording")

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    stream.write(data, CHUNK)

print("* done")

stream.stop_stream()
stream.close()

p.terminate()
"""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')

p = pyaudio.PyAudio()

def callback(in_data, frame_count, time_info, status):
    data = wf.readframes(frame_count)
    return (data, pyaudio.paContinue)

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

stream.start_stream()

while stream.is_active():
    time.sleep(0.1)

stream.stop_stream()
stream.close()
wf.close()

p.terminate()
"""
PyAudio Example: Make a wire between input and output (i.e., record a
few samples and play them back immediately).

This is the callback (non-blocking) version.
"""

import pyaudio
import time

WIDTH = 2
CHANNELS = 2
RATE = 44100

p = pyaudio.PyAudio()

def callback(in_data, frame_count, time_info, status):
    return (in_data, pyaudio.paContinue)

stream = p.open(format=p.get_format_from_width(WIDTH),
                channels=CHANNELS,
                rate=RATE,
                input=True,
                output=True,
                stream_callback=callback)

stream.start_stream()

while stream.is_active():
    time.sleep(0.1)

stream.stop_stream()
stream.close()

p.terminate()
"""PyAudio Example: Mac OS X-only: Play a wave file with channel maps."""

import pyaudio
import wave
import sys

chunk = 1024

PyAudio = pyaudio.PyAudio

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')

p = PyAudio()

# 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, # default
        channel_map=channel_map)
except AttributeError:
    print("Sorry, couldn't find PaMacCoreStreamInfo. Make sure that "
          "you're running on Mac OS X.")
    sys.exit(-1)

print("Stream Info Flags:", stream_info.get_flags())
print("Stream Info Channel Map:", stream_info.get_channel_map())

# open stream
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)

# read data
data = wf.readframes(chunk)

# play stream
while data != '':
    stream.write(data)
    data = wf.readframes(chunk)

stream.stop_stream()
stream.close()

p.terminate()

License

PyAudio is distributed under the MIT License. That is to say,

Copyright (c) 2006-2014 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.

Acknowledgements

The development of PyAudio was funded in part by the Cambridge-MIT Institute and T-Party.

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, and Jason Roehm for their much appreciated suggestions and patches—as well as to others who have written to say hello!

Special thanks to Justin Mazzola Paluska and Felipe Sateler for Debian/Ubuntu packaging help.

Translations

Contact

For help with PyAudio, your best bet for a timely response is to consult or post to StackOverflow.

Comments, suggestions, and patches welcomed. Send mail to my first name at mit.edu.

hubert