Open an interactive online version by clicking the badge Binder badge or download the notebook.

Impulse response measurement#

Marco Berzborn (1), Simon Kersten (2)
(1) Department of the Built Environment, Eindhoven University of Technology
(2) Institute for Hearing Technology and Acoustics, RWTH Aachen University

Contact: m.berzborn@tue.nl, simon.kersten@akustik.rwth-aachen.de

Measuring impulse responses is a frequent task in acoustics, because impulse responses completely characterize the linear behavior of a system in both the time and frequency domains. For example, room impulse responses are often used to compute room acoustic parameters and loudspeaker impulse responses often serve as a basis for designing equalization filters. In this notebook, you will measure a room impulse response and compare an exponential sine sweep with pink noise as excitation signals. You will choose a suitable output level, record and inspect the system response, compute the impulse response using spectral deconvolution, and improve the signal-to-noise ratio by averaging repeated measurements and by using longer excitation signals. Throughout the notebook, you will discuss practical aspects such as the sensitivity to noise and nonlinearities.

Duration: 90 Minutes

Requirements: Familiarity with digital signal processing fundamentals. A loudspeaker and a microphone connected to your computer.

References
Kirkeby, O., & Nelson, P. A. (1999). Digital filter design for inversion problems in sound reproduction. Journal of the Audio Engineering Society, 47(7/8), 583–595. https://www.aes.org/e-lib/browse.cfm?elib=12098
Müller, S., & Massarani, P. (2001). Transfer-function measurement with sweeps: Director’s cut including previously unreleased material and some corrections. Original work published in Journal of the Audio Engineering Society, 49(6), 443–471.
Norcross, S. G., Bouchard, M., & Soulodre, G. A. (2006). Inverse filtering design using a minimal-phase target function from regularization (Convention Paper No. 6929). 121st Audio Engineering Society Convention, San Francisco, CA, United States.
Dependencies
pip install pyfar>=0.8 sounddevice ipympl watermark
[ ]:
import pyfar as pf
import numpy as np
import matplotlib.pyplot as plt

%matplotlib ipympl

Configuration#

Before starting the measurements, configure the measurement parameters and select the audio interface. The examples below use CoreAudio on macOS as the default configuration. On Windows, you can use an ASIO or WASAPI device instead. The available audio interfaces and their corresponding host APIs depend on your operating system and installed audio drivers.

Note: If you want to use ASIO on Windows, you need to enable ASIO support before importing sounddevice via os.environ["SD_ENABLE_ASIO"] = "1". Uncomment the line in the cell below if you intend to use an ASIO device.

Task: Adapt the settings to match your hardware.

[ ]:
import os

# Enable ASIO support on Windows before importing sounddevice
# os.environ["SD_ENABLE_ASIO"] = "1"

import sounddevice as sd
[ ]:
# Measurement settings
sampling_rate = 44100       # Sampling rate in Hz

# List available audio interfaces and their host APIs
sd.query_devices()
[ ]:
# Select the audio interface.
# Replace the example with the exact device name shown by sd.query_devices().
sd.default.device = "Your audio interface name"

# Default audio settings: (number of input channels, number of output channels)
sd.default.samplerate = sampling_rate
sd.default.channels = (1, 1)

# Physical channel numbers (sounddevice mappings are one-based)
input_channel = 1
output_channel = 1

# Optional macOS CoreAudio settings.
# Use these to request the device to change its sampling rate rather than
# silently resampling, and raise an error if conversion would be required.
#
# sd.default.extra_settings = sd.CoreAudioSettings(
#     change_device_parameters=True,
#     fail_if_conversion_required=True)

print("Selected device:", sd.default.device)
print("Sampling rate:", sd.default.samplerate)
print("Default channel counts:", sd.default.channels)
print("Input channel mapping:", [input_channel])
print("Output channel mapping:", [output_channel])

Using these settings, we define a helper function record_signal to play and recorded a `pyfar.Signal <https://pyfar.readthedocs.io/en/stable/classes/pyfar.audio.html#pyfar.Signal>`__.

[ ]:
def record_signal(s):
    """Play a pyfar signal and return the recorded signal as a pyfar.Signal."""
    recording= sd.playrec(
        s.time.T,
        samplerate=sampling_rate,
        input_mapping=[input_channel],
        output_mapping=[output_channel],
        blocking=True)
    recorded_signal = pf.Signal(recording[:, 0].T, s.sampling_rate)
    return recorded_signal

Theory#

The impulse response \(h[k]\) relates any input or excitation signal \(s[k]\) of a system (e.g. a room or loudspeaker) to the output \(y[k]\) that can be recorded with a microphone. Formally this link is given by the convolution

\[y[k] = s[k] \ast h[k]\,.\]

Several aspects need to be carefully considered in acoustical measurement practice, including the bandwidth and spectral energy distribution of the excitation signal and its inversion.

Excitation signals#

Theoretically any signal can be used for excitation, however there are a few requirements that should be considered for acoustical measurements. The excitation signals should

  • be broad band, that is, it should cover the frequency range of interest for example the range of human hearing starting at 20 Hz and going up to 20 kHz

  • contain enough energy to achieve a sufficient signal-to-noise ratio in the measured impulse response

  • be robust to acoustic noise

  • be robust to non-linear distortion that can appear due to non-ideal sound sources (loudspeakers)

Short pulses#

Exciting a system with a perfect impulse of infinitely short duration and defined energy is only possible in theory. A pulse of short duration and certain magnitude is a first practical approximation which may fulfill the criteria above. However, the key limitation for this approach is that the excitation needs to be with a certain amount of energy to be above noise level. So given a short duration close to the ideal case, a very high magnitude is required, which usually drives the system or measurement equipment into the nonlinear regime causing effects such as distortions. Therefore, better choices exist for impulse response measurements.

The two most important are random noise signals and sine sweeps.

Random noise signals#

In the time domain, random noise signals have a random waveform with high peaks compared to their RMS level, which limits the energy that fits below the maximum amplitude. In the frequency domain, their spectrum follows the chosen shape only on average: the magnitude of a single realization fluctuates randomly, with dips at individual frequencies. Their bandwidth can be freely chosen by filtering and their energy can be adjusted by changing the length of the signal. The pink noise used below is not bandlimited, it contains energy up to half the sampling rate.

Sine sweeps#

Sine sweeps are sine signals with a continuously changing frequency that satisfy all the conditions given above. Like noise signals, their bandwidth can be freely chosen and their energy can be adjusted by changing the length of the sweep signal. The key advantages compared to noise signals are their superior immunity to measurement noise (broadband and impulsive) and time variance, suitability for non-linearity rejection, and high flexibility in controlling the energy distribution over frequency. They are therefore the predominant excitation signal for acoustical measurements.

Comparison of pink noise and sine sweep#

We will start with the example of an exponential sine sweep designed in the time domain and compare it with a pink noise signal.

Task: Create the two excitation signals, stored in s_noise and s_sweep, using the pyfar.signals module. Ensure that both signals have the RMS given by rms_target using pyfar.dsp.normalize to control their output level. Start at -40 dBFS, you will adjust the level in the following tasks. Use the parameters provided.

Note: pyfar.signals.noise returns a signal with the FFT normalization 'rms'. The provided code changes the FFT normalization to 'none', which is required for the inversion below.

[ ]:
frequency_range_sweep = [20, 20e3]
n_samples = 2**18
sampling_rate = 44100
rms_target = 10 ** (-40 / 20)  # dBFS to amplitude conversion

# YOUR CODE HERE
raise NotImplementedError()

# pf.signals.noise returns fft_norm='rms', change it to 'none'
s_noise.fft_norm = 'none'

# a peak above 1 clips at the output
print(f"Peak of the noise: {np.abs(s_noise.time).max():.3f}")
print(f"Peak of the sweep: {np.abs(s_sweep.time).max():.3f}")

plt.figure()
ax = pf.plot.time_freq(s_noise, label="Pink noise")
pf.plot.time_freq(s_sweep, label="Sine sweep")
ax[1].legend()
plt.show()

Task: Listen to the signals using sounddevice.play with blocking=True. You can use your default output device, or select and set it via sounddevice.query_devices and sounddevice.default.device. The time data and sampling rate of the signals can be accessed via their class properties.

Starting at -40 dBFS, raise rms_target in small steps and execute the cell above and the listening cells again, until both signals are clearly audible. Pink noise has much higher peaks than a sweep with the same RMS level, so check the printed peaks: values above 1 clip at the output.

Watch your output level before continuing!

[ ]:
# listen to the noise signal
# YOUR CODE HERE
raise NotImplementedError()
[ ]:
# listen to the sweep signal
# YOUR CODE HERE
raise NotImplementedError()

Discussion: How do the two signals sound? Compare their spectra: how is the energy distributed over frequency, how smooth are the spectra, and what happens outside the frequency range of the sweep?

Recording the system response#

The system response can be obtained by playing the excitation signal through a loudspeaker and recording it with a microphone. Yet, we need to record for longer than it takes the system response to decay. Therefore, the excitation signal is padded with zeros.

Zero-padding#

In this example, we measure a room impulse response. A conservative option is to pad zeros according to the expected reverberation time and delay due to finite speed of sound (propagation delay). We pad one second of zeros in this case.

Task: Implement the zero padding for the noise and sweep signals using pyfar.dsp.pad_zeros and store the results in s_noise_padded and s_sweep_padded.

[ ]:
# YOUR CODE HERE
raise NotImplementedError()

plt.figure()
ax = pf.plot.time(s_noise_padded, label="Pink noise")
pf.plot.time(s_sweep_padded, label="Sine sweep")
ax.legend()
plt.show()

Recording#

Task: Use the helper function record_signal to record the room response, and store the recordings in y_noise and y_sweep. It is always a good idea to monitor the measurement by means of a time-frequency plot. Adjust the level until the recorded level is sufficient without clipping the microphone input, either with adjusting rms_target for creating the signals above, or with the gain of the microphone input. A printed peak close to 1 means that the input clips. If you change rms_target, execute the zero-padding cell again as well, because it creates separate signals.

Watch your output and input level before continuing!

[ ]:
# YOUR CODE HERE
raise NotImplementedError()

# a peak close to 1 means that the input clips
print(f"Recorded peak of the noise: {np.abs(y_noise.time).max():.3f}")
print(f"Recorded peak of the sweep: {np.abs(y_sweep.time).max():.3f}")

plt.figure()
ax = pf.plot.time_freq(y_noise, label="Pink noise")
pf.plot.time_freq(y_sweep, label="Sine sweep")
ax[1].legend()
plt.show()

Task: Plot the spectrograms of y_noise and y_sweep using pyfar.plot.spectrogram.

[ ]:
# YOUR CODE HERE
raise NotImplementedError()

Discussion: Compare the recordings of both signals in the time domain, the frequency response and the spectrogram. What do the plots tell you about the system and the background noise? Which features of the excitation signal can you recognize in each recording? What do you see in the spectrogram of the sweep that is not part of the excitation signal, what could cause it, and why can you not see it for the noise?

Spectral deconvolution#

The naive approach to compute the impulse response would be to do an inverse convolution in the time domain. However, it is more efficient and flexible to do a frequency domain deconvolution (Müller & Massarani, 2001). Applying the Fourier Transform to the convolution \(y[k] = s[k] \ast h[k]\) yields

\[Y[\mu] = H[\mu] S[\mu]\]

with capital letters denoting complex spectra and \(\mu\) the index of the discrete frequency bins. The transfer function (Fourier Transform of the impulse response) can now be computed as

\[H[\mu] = \frac{Y[\mu]}{S[\mu]} = Y[\mu]\cdot G[\mu]\,.\]

While this looks simple, it requires the direct inversion of the excitation signal, \(G[\mu] = 1/S[\mu]\), which should often be avoided. The plot below shows the direct inversion of both excitation signals.

[ ]:
plt.figure()
ax = pf.plot.freq(1 / s_noise_padded, label="Inverted pink noise signal")
pf.plot.freq(1 / s_sweep_padded, label="Inverted sweep signal")
ax.set_title("Direct inversion of the excitation signal")
plt.show()

Regularized spectrum inversion#

Since the sweep is bandlimited, its direct inversion will boost out of band noise. To avoid this, a regularized inversion can be applied (Kirkeby & Nelson, 1999; Norcross et al., 2006). The regularized inversion is defined as

\[G_\lambda[\mu] = \frac{S^*[\mu]}{|S[\mu]|^2 + \lambda[\mu]}, \qquad \lambda[\mu] = \beta\,|\epsilon[\mu]|^2\]

with the complex conjugate \(^*\), the regularization parameter \(\lambda[\mu]\), a scaling factor \(\beta\), and the frequency-dependent regularization function \(\epsilon[\mu]\).

Here, the regularization only acts outside the chosen frequency range, while the inversion inside the range is identical to the direct inversion. The magnitude spectrum of the pink noise fluctuates, so its inversion boosts the frequencies at the dips, and these remain inside the range.

Task: Compute the regularized inversion of both excitation signals using `pyfar.dsp.RegularizedSpectrumInversion <https://pyfar.readthedocs.io/en/stable/modules/pyfar.dsp.html#pyfar.dsp.RegularizedSpectrumInversion>`__. Use its from_frequency_range method with the given frequency_range_regularization and beta="energy", and its invert property. Store the results in s_noise_inverted and s_sweep_inverted. How does the regularization change the inversion of each signal?

[ ]:
frequency_range_regularization = [20, 20e3]

# YOUR CODE HERE
raise NotImplementedError()

plt.figure()
ax = pf.plot.freq(
    1 / s_noise_padded, label="Noise, direct", color="C0", alpha=0.3
)
pf.plot.freq(s_noise_inverted, label="Noise, regularized", color="C0")
pf.plot.freq(1 / s_sweep_padded, label="Sweep, direct", color="C1", alpha=0.3)
pf.plot.freq(s_sweep_inverted, label="Sweep, regularized", color="C1")
ax.set_title("Direct and regularized inversion of the excitation signal")
ax.legend()
plt.show()

Calculation of the impulse response#

The transfer function is now computed by a spectral multiplication of the recorded spectrum with the carefully inverted excitation signal \(G[\mu]\)

\[\hat H[\mu]=Y[\mu]\,G[\mu]\]

and the impulse response is given by the inverse Fourier Transform

\[\hat h[k]=\mathrm{F}^{-1}\{\hat H[\mu]\}\]

In pyfar, the frequency domain multiplication is overloaded by the * operator and can thus elegantly be realized in a single line.

Task: Calculate the impulse responses measured with both excitation signals, using the direct and the regularized inversion. Store them in h_noise_direct, h_noise_regularized, h_sweep_direct and h_sweep_regularized, which are used by the plot below. Compare the results in the time and frequency domain.

[ ]:
# YOUR CODE HERE
raise NotImplementedError()

# plot result
plt.figure()
ax = pf.plot.time_freq(
    pf.utils.concatenate_channels(
        [
            h_noise_direct,
            h_noise_regularized,
            h_sweep_direct,
            h_sweep_regularized,
        ]
    ),
    dB_time=True,
    label=[
        "Pink noise, direct",
        "Pink noise, regularized",
        "Sine sweep, direct",
        "Sine sweep, regularized",
    ],
)
ax[1].legend()
plt.show()

Time windowing#

After an impulse response has decayed into the noise floor, the remaining samples mainly contain noise. A time window with a fade-out removes this part of the impulse response.

Task: Inspect the regularized impulse responses from the plot above and choose the time interval in which the window should fade out. Apply the window to both impulse responses using pyfar.dsp.time_window and store the results in h_noise_windowed and h_sweep_windowed, which are used by the plot below.

Hint: Use the pyfar interactive shortcuts to zoom in on the impulse responses.

[ ]:
# YOUR CODE HERE
raise NotImplementedError()

plt.figure()
ax = pf.plot.time_freq(
    pf.utils.concatenate_channels(
        [
            h_noise_regularized,
            h_noise_windowed,
            h_sweep_regularized,
            h_sweep_windowed,
        ]
    ),
    dB_time=True,
    label=[
        "Pink noise",
        "Pink noise, windowed",
        "Sine sweep",
        "Sine sweep, windowed",
    ],
)
ax[1].legend()
plt.show()

Discussion: How much of the noise can the time window remove from the impulse responses, and which part of it remains? By how much do the results improve for the pink noise and the exponential sweep in the time and frequency domain, and why do they differ?

[ ]:
plt.figure()
ax = pf.plot.spectrogram(h_noise_regularized)
ax[0][0].set_title("Pink noise")
plt.show()

plt.figure()
ax = pf.plot.spectrogram(h_sweep_regularized)
ax[0][0].set_title("Sine sweep")
plt.show()

Note that the level of the impulse response and transfer function are arbitrary because the measurement was not calibrated to an absolute sound pressure level. Hence, measuring with different output level, microphone amplification, or distance to the sound source would change the level.

Effect of excitation signal selection#

Discussion: Compare the impulse responses measured with both excitation signals. Which one has the lower noise floor at the same RMS level? Where does the energy of the distortion products end up for each signal? Which excitation signal would you choose for this measurement, and why?

Distortion products#

The additional sweeps in the spectrogram of the recorded sweep are distortion products caused by the weakly nonlinear loudspeaker. Their frequency is a multiple of the instantaneous frequency of the excitation signal. The deconvolution compresses each of them into a separate harmonic impulse response that precedes the linear impulse response. Due to the periodicity of the discrete Fourier transform, they appear at the end of the measured impulse response. For the noise signal, the distortion products cannot be separated and spread over the entire impulse response. The postprocessing notebook shows how to calculate the positions of the harmonic impulse responses.

Improving the signal-to-noise ratio#

There are two essential approaches to improve the signal-to-noise ratio (SNR): averaging repeated measurements and increasing the length of the excitation signal.

Averaging \(M\) synchronized repetitions leaves the time-invariant system response unchanged, while the noise power reduces to \(1/M\), as long as the noise is independent between repetitions. A sweep that is \(M\) times as long and has the same RMS level contains \(M\) times the energy, which reduces the noise power in the impulse response by the same factor. For both approaches, the expected SNR gain is therefore (Müller & Massarani, 2001)

\[\Delta\text{SNR} = 10\log_{10} M \;\text{dB}\,.\]

Averaging consecutive measurements#

Task: Record n_averages consecutive repetitions of the padded sweep and append them to the list y_sweeps. You can change n_averages to explore its effect. The provided code then combines them into a single signal with one channel per repetition.

[ ]:
n_averages = 3
y_sweeps = []
# YOUR CODE HERE
raise NotImplementedError()

y_sweeps = pf.utils.concatenate_channels(y_sweeps)

Task: Average the recordings using pyfar.dsp.average. Calculate the impulse response of the first repetition y_sweeps[0] and store it in h_sweep_single, and calculate the impulse response of the average and store it in h_sweep_avg.

[ ]:
# YOUR CODE HERE
raise NotImplementedError()

Increasing the length of the excitation signal#

Task: Create a sweep that is n_averages times as long as s_sweep, with the same frequency range and RMS level, and pad one second of zeros. Compute its regularized inversion with frequency_range_regularization. Store the results in s_sweep_extended_padded and s_sweep_extended_inverted. Then record the system response in y_sweep_extended and store the impulse response in h_sweep_extended.

[ ]:
# YOUR CODE HERE
raise NotImplementedError()

Use this code cell to execute the measurement to avoid re-running the measurement when changing the pre- and post-processing steps.

[ ]:
# YOUR CODE HERE
raise NotImplementedError()

Implement the deconvolution in the cell below and plot the results.

[ ]:
# YOUR CODE HERE
raise NotImplementedError()

plt.figure()
ax = pf.plot.time(h_sweep_single, label="Single sweep", dB=True)
pf.plot.time(h_sweep_avg, label=f"{n_averages} averages", dB=True)
pf.plot.time(h_sweep_extended, label=f"{n_averages} times as long", dB=True)
# the extended impulse response is longer, compare the same time range
ax.set_xlim(0, h_sweep_single.times[-1])
ax.legend()
plt.show()

Discussion: How well does the noise floor of both approaches match the expected SNR gain? How long does each of the two measurements take, including the padded zeros? Which approach would you choose if the system changes slightly over time, for example due to moving air or temperature changes?

Bonus: SNR improvement with pink noise#

Task: Repeat the comparison of both approaches with pink noise, using the same n_averages and RMS level as for the sweep.

For the averaging, record n_averages consecutive repetitions of the same signal s_noise_padded and append them to the list y_noises, so that s_noise_inverted can be used for all of them. Average the recordings, then store the impulse response of the first repetition in h_noise_single and the impulse response of the average in h_noise_avg.

[ ]:
y_noises = []
# YOUR CODE HERE
raise NotImplementedError()

y_noises = pf.utils.concatenate_channels(y_noises)
[ ]:
# YOUR CODE HERE
raise NotImplementedError()

Task: For the longer signal, create pink noise that is n_averages times as long as s_noise, normalize it to the same RMS level, pad one second of zeros and store the result in s_noise_extended_padded. Record the system response in y_noise_extended. Compute the regularized inversion with frequency_range_regularization in s_noise_extended_inverted and store the impulse response in h_noise_extended.

[ ]:
# YOUR CODE HERE
raise NotImplementedError()

# pf.signals.noise returns fft_norm='rms', the inversion below needs 'none'
s_noise_extended_padded.fft_norm = 'none'
[ ]:
# YOUR CODE HERE
raise NotImplementedError()
[ ]:
# YOUR CODE HERE
raise NotImplementedError()

plt.figure()
ax = pf.plot.time(h_noise_single, label="Single noise", dB=True)
pf.plot.time(h_noise_avg, label=f"{n_averages} averages", dB=True)
pf.plot.time(h_noise_extended, label=f"{n_averages} times as long", dB=True)
pf.plot.time(
    h_sweep_avg, label=f"Sweep, {n_averages} averages", dB=True, color="grey"
)
# the extended impulse response is longer, compare the same time range
ax.set_xlim(0, h_noise_single.times[-1])
ax.legend()
plt.show()

Discussion: How well do the two approaches match the expected SNR gain for pink noise, and why might the result of a single measurement differ from it? How does the noise floor compare with that of the sweep at the same RMS level? How long do you need to measure with each signal to achieve the same quality?

License notice#

This notebook © 2026 by Marco Berzborn and Simon Kersten is licensed under CC BY 4.0

Watermark#

The following watermark might help others to install specific package versions that might be required to run the notebook. Please give at least the versions of Python, IPython, numpy , and scipy, major third party packagers (e.g., pytorch), and all used pyfar packages.

[ ]:
%load_ext watermark
%watermark -v -m -p numpy,scipy,pyfar,sofar,sounddevice,watermark