HOWTO · Python
How to Process Real-Time Audio in Python
Learn how to capture audio in Python with PyAudio, process it in blocks, and manage latency, stream setup, and device troubleshooting.
On this page
Real-time audio processing means handling each incoming block quickly enough to keep a live input-to-output stream moving. It does not mean zero delay: the audio device, buffer size, operating system, and processing work all contribute latency. Python with PyAudio can capture and play device audio, while Python signal-processing libraries can analyze or transform each block between those steps.
Real-Time Audio Processing in Python
An audio interface or built-in device converts an analog microphone or instrument signal into digital samples. A Python program reads those samples in blocks, applies a computation, then writes the result to an output stream. This pattern is useful for monitoring, simple effects, and analysis, but a general-purpose Python process and desktop audio stack do not guarantee hard real-time deadlines. For an interactive effect, measure the complete input-to-output delay on the target system.
Install PyAudio and Prepare an Audio Device
Install PyAudio in the Python environment used by the application with python -m pip install pyaudio. Installation may depend on the operating system, Python version, and available audio or compiler libraries; follow the package’s platform-specific instructions if pip cannot build or install it. Connect or enable an input and output device, and check that the operating system grants the application microphone access.
When opening streams, choose a sample rate supported by the device, the number of channels it exposes, a sample format such as 16-bit integer PCM, and a frames_per_buffer value. A frame contains one sample per channel, so a mono block of 256 frames has 256 samples, while a stereo block has 512 sample values. Input and output settings must be compatible with the data passed between them. Device indices and supported formats vary; query the available devices and test the chosen configuration instead of assuming a particular default device.
Capture and Play Audio in Blocks
The basic stream loop is: open an input stream and an output stream, read one block from the input, process it, write a same-duration block to the output, and close both streams when finished. The following runnable arithmetic model demonstrates gain processing with two blocks of sample values. It is separate from the device-backed workflow below and does not access a microphone or speaker.
Run this example:
blocks = [[1000, -1000], [2000, -2000]]
gain = 0.5
for number, block in enumerate(blocks, start=1):
processed = [int(sample * gain) for sample in block]
print(f"Block {number}: {processed}")
Block 1: [500, -500]
Block 2: [1000, -1000]
This device-backed function captures 100 mono blocks of signed 16-bit PCM at 44.1 kHz, halves each sample’s amplitude with clipping protection, and sends the modified blocks to playback. It is shown as an unexecuted hardware example; the supplied runtime output above belongs only to the arithmetic model. Set the input and output device indices to compatible devices if the system defaults are unsuitable, and use a sample rate and channel configuration both devices support. The function opens the input before output, so if either open or later processing fails, its finally block attempts to stop and close every stream that opened and to terminate PyAudio.
def run_audio(input_device_index=None, output_device_index=None,
sample_rate=44100, frames_per_buffer=256, blocks=100, gain=0.5):
import struct
import pyaudio
audio = pyaudio.PyAudio()
input_stream = None
output_stream = None
try:
input_stream = audio.open(
format=pyaudio.paInt16,
channels=1,
rate=sample_rate,
input=True,
input_device_index=input_device_index,
frames_per_buffer=frames_per_buffer,
)
output_stream = audio.open(
format=pyaudio.paInt16,
channels=1,
rate=sample_rate,
output=True,
output_device_index=output_device_index,
frames_per_buffer=frames_per_buffer,
)
sample_format = f"<{frames_per_buffer}h"
for _ in range(blocks):
input_bytes = input_stream.read(frames_per_buffer)
samples = struct.unpack(sample_format, input_bytes)
processed = tuple(
max(-32768, min(32767, round(sample * gain)))
for sample in samples
)
output_stream.write(struct.pack(sample_format, *processed))
finally:
try:
if input_stream is not None:
try:
input_stream.stop_stream()
finally:
input_stream.close()
finally:
try:
if output_stream is not None:
try:
output_stream.stop_stream()
finally:
output_stream.close()
finally:
audio.terminate()
After confirming the device settings, call run_audio() or pass supported device indices. The example processes a finite number of blocks and then returns; it is pass-through in timing but not in amplitude, because the gain step halves the signal. It does not generate sound independently, and its audible result depends on the microphone input, device routing, and volume.
Add Signal Processing to the Audio Stream
Insert the processing step after reading a block and before writing it. For frequency analysis, an FFT converts a time-domain block into frequency components; see the FFT algorithm for a related example. An FFT result is analysis data and does not itself create an audible effect. To change what a listener hears, transform the samples and convert them back to the format expected by the output stream, taking care to avoid clipping and to preserve the block’s duration.
MFCCs summarize spectral characteristics often used as features in speech-recognition systems. LPC models aspects of a signal’s spectral envelope and is used in speech and audio analysis. These methods serve different purposes and have different computation costs; neither is automatically suitable for a low-latency effect. If a block takes longer to process than its playback duration, buffers can accumulate and latency grows.
Manage Latency and Troubleshoot Common Problems
The nominal duration of a block is frames_per_buffer / sample_rate seconds. For example, 256 frames at 44,100 frames per second represent about 5.8 milliseconds of audio per block. Smaller blocks can reduce buffering delay, but they increase how often Python and the audio backend must handle callbacks or reads and writes. If the system cannot keep up, audio may drop out. Larger blocks give more processing time per call but add buffering delay. Choose a supported block size, then measure and listen on the intended device.
If opening a stream fails, verify that PyAudio is installed in the active environment, the selected device exists, microphone permission is enabled, and the requested sample rate, channel count, and format are supported. If playback is silent or distorted, confirm that the input is connected, the output device is correct, and the bytes use the expected sample format and channel layout. Keep processing bounded, avoid slow disk or network work inside the audio loop, and close streams during cleanup so a later run can reopen the device. These checks help isolate setup problems from processing that simply cannot finish within the chosen block interval.