Resampling 48 kHz to 44.1 kHz in Python: SciPy resample_poly, Anti-Aliasing, and Edge Handling

Convert 48 kHz to 44.1 kHz with SciPy resample_poly, design a Kaiser FIR to suppress aliasing, and measure how padtype affects the edges of a finite recording.

Convert 48 kHz to 44.1 kHz with SciPy

For a 48 kHz NumPy array, use signal.resample_poly(x, up=147, down=160, axis=0). With stereo audio shaped as (samples, channels), use axis=0 as well. Use axis=-1 when time is on the last axis. Convert integer PCM to floating point before processing, then handle scaling and quantization when writing the result.

One second of input contains 48,000 samples and produces 44,100 output samples. Build the new time axis with np.arange(len(y)) / 44_100 and write 44,100 Hz in the audio file header. Changing the header alone changes playback speed and pitch.

Why the conversion uses 147 and 160

The output rate is \(L/M\) times the input rate. The greatest common divisor of 48,000 and 44,100 is 300, which gives \(L=147\) and \(M=160\) .

StageSample ratePurpose
Input48,000 HzOriginal samples
Upsample by 1477,056,000 HzInsert zeros at intermediate times, creating spectral images
Low-pass FIR7,056,000 HzSuppress spectral images and frequencies that would alias after decimation
Downsample by 16044,100 HzKeep samples at the required output times

The table describes the operations conceptually. Polyphase filtering computes the terms needed for each requested output instead of materializing a large array of inserted zeros. The sampling theorem article explains how these spectral copies fold.

The output Nyquist frequency is 22,050 Hz. If a 22,100 Hz input tone survives the filter, it appears at \(44{,}100-22{,}100=22{,}000\) Hz in the output. At that point its frequency is indistinguishable from a genuine 22,000 Hz component.

Design a filter that keeps 20 kHz and suppresses 22.05 kHz and above

Suppose you need to retain the 20 kHz input component and achieve about 80 dB of stopband attenuation from 22,050 Hz onward. The transition band is 20,000–22,050 Hz. The code asks the Kaiser design for 84 dB to give the design some margin and then measures the resulting response.

When passing a coefficient array as window in resample_poly, design the FIR at the intermediate rate after upsampling by the reduced ratio. Here, that rate is 7,056,000 Hz. Divide the transition width in hertz by the intermediate Nyquist frequency for kaiserord. The single cutoff in firwin is the half-amplitude point, so use 21,025 Hz, the middle of the transition band. Symmetric, odd-length coefficients fit SciPy’s output centering. resample_poly documentation , firwin documentation , kaiserord documentation

from math import gcd

import numpy as np
from scipy import signal

fs_in, fs_out = 48_000, 44_100
g = gcd(fs_in, fs_out)
up, down = fs_out // g, fs_in // g
fs_fir = fs_in * up

pass_edge, stop_edge = 20_000, 22_050
width = (stop_edge - pass_edge) / (fs_fir / 2)
numtaps, beta = signal.kaiserord(84, width)
if numtaps % 2 == 0:
    numtaps += 1

h = signal.firwin(
    numtaps,
    (pass_edge + stop_edge) / 2,
    fs=fs_fir,
    window=("kaiser", beta),
)

t_in = np.arange(3 * fs_in) / fs_in
x = np.cos(2 * np.pi * 20_000 * t_in) + np.cos(2 * np.pi * 22_100 * t_in)

def tone_db(samples, frequency):
    # Use the middle second, away from the filtering transients at both ends.
    middle = samples[fs_out : 2 * fs_out]
    t = np.arange(middle.size) / fs_out
    amplitude = 2 * abs(np.mean(middle * np.exp(-2j * np.pi * frequency * t)))
    return 20 * np.log10(max(amplitude, np.finfo(float).tiny))

for label, y in (
    ("default", signal.resample_poly(x, up, down)),
    ("custom", signal.resample_poly(x, up, down, window=h)),
):
    assert len(y) == 3 * fs_out
    print(label, f"{tone_db(y, 20_000):.3f} dB", f"{tone_db(y, 22_000):.3f} dB")

f, response = signal.freqz(h, worN=2**20, fs=fs_fir)
pass_db = 20 * np.log10(np.abs(response[f <= pass_edge]))
stop_max = np.max(np.abs(response[f >= stop_edge]))
print("taps:", numtaps)
print("worst passband deviation:", np.max(np.abs(pass_db)), "dB")
print("largest stopband gain:", 20 * np.log10(stop_max), "dB")

In SciPy 1.18.1, the simulation gives the following amplitudes relative to a unit-amplitude input tone. The measurement uses the middle second, away from the filtering transients at the edges. The two measured frequencies complete whole cycles in that interval, which keeps them orthogonal for this amplitude measurement. Short or noncoherent records need more care around leakage and windowing. See the guide to FFT amplitude scaling .

FilterDesired 20 kHz tone22 kHz alias from the 22.1 kHz input tone
SciPy default−0.826 dB−6.235 dB
Custom Kaiser FIRApproximately 0 dB−84.811 dB

The custom filter has 18,235 taps. On the frequency grid, the maximum absolute passband deviation is about 0.0006 dB and the maximum stopband gain is about −83.9 dB. The grid check covers more of the stopband than the single-tone experiment. A wider transition band allows a shorter filter when your application can accept a lower passband edge. The default result here is for a tone just above the output Nyquist limit. Attenuation varies across the stopband.

Check padtype when the beginning or end looks wrong

Near an edge, the filter needs values outside the recording. The default padtype="constant" assumes zero there. For a ramp that keeps rising outside the observation interval, padtype="line" continues the line through the first and last input points.

import numpy as np
from scipy import signal

ramp = np.linspace(1.0, 2.0, 480)
for pad in ("constant", "line"):
    y = signal.resample_poly(ramp, 147, 160, padtype=pad)
    t_as_input_index = np.arange(y.size) * 160 / 147
    expected = 1 + t_as_input_index / (len(ramp) - 1)
    edge_error = np.r_[y[:8] - expected[:8], y[-8:] - expected[-8:]]
    print(pad, f"max edge error = {np.max(np.abs(edge_error)):.6f}")

Across the first and last eight output samples, the maximum absolute error is 0.040237 with constant and 0.000260 with line. This example favors linear extrapolation because the underlying signal is a ramp. For a short audio clip or a signal captured around an event, check whether you can include real samples before and after the interval of interest. Applying resample_poly independently to successive blocks introduces a new boundary assumption for each block and may reset the sampling phase. Continuous processing needs a design that carries the FIR history and decimation phase across blocks.

FAQ

What up and down factors convert 48 kHz to 44.1 kHz?

Use up=147 and down=160. Divide 44,100 and 48,000 by their greatest common divisor, 300.

What sample rate should I use to design the FIR for resample_poly?

Multiply the input rate by the reduced up factor. Here, \(48{,}000\times147=7{,}056{,}000\) Hz. Pass that value as fs to firwin so the cutoff can be expressed in hertz.

Does padtype line remove edge errors?

It reduces the edge error in the ramp example. With measured data, its effectiveness depends on how well a straight line approximates the signal beyond both edges.