Moving talkers

Three talkers speak at once, one straight ahead and one 40° to each side. Which one do you follow? If the one ahead moves, does that help, and how does it compare with a voice that differs from the other two? Cho & Kidd (2022) asked about motion with stimuli like the ones on this page, made with sonore's predecessor sigtools.

  • The talkers and the trajectories: the target sentence read by the male and by the female talker, the maskers, and the paths the target takes.
  • One talker, moving: what motion alone sounds like.
  • Three talkers: the male or the female target among two male or two female maskers, standing still and then swinging back and forth in azimuth.
  • Coming closer: a talker walking up to the listener, without and with a room.
  • Passing by: a buzz going past at 15 m/s, and the Doppler glide of its pitch.
  • Straight paths across the plane: the buzz in front, close by, down the side, behind, crossing at an angle and coming straight at the listener.
  • A path no source could take: the buzz jumping around the head far faster than anything can move, and what the renderer makes of it.
  • How the motion is rendered: filtering with HRIRs that change over time, without clicks or comb filtering.

A "cocktail party" has two to six talkers walking around the listener for 20 to 30 s. For the interaural cues one at a time, timing alone and correlation that changes, see Binaural cues.

Every sound here is rendered through measured head-related impulse responses (HRIRs) of a KEMAR manikin at eight distances from 20 cm to 1.6 m (Qu et al., 2009), so listen with headphones. Farther than 1.6 m, distance changes only the travel time and the level.

Press play and a line follows the sound across every time axis in its plots. Click any time axis to play from that point. The audio is lossless, since compression would alter the binaural sounds. Start with your volume low.

To run this page yourself, open it as a notebook in Colab or download it. It is the same code, and it fetches the recordings it needs from the sonore repository.

The talkers and the trajectories

The target is the sentence from Seeing speech, read by the male talker and by the female talker of What is a voice. There are two sets of maskers. The male maskers are two sentences by a third talker in the CMU ARCTIC corpus, also male (Kominek & Black, 2004). The corpus files here hold no other female sentences, so the female maskers are the opening seconds of two audiobook passages read by female readers in LibriSpeech (Panayotov et al., 2015), cut between words to about the lengths of the male maskers; they are read aloud like the sentences, but recorded differently. Sources are in docs/speech/SOURCES.md. Every recording is scaled to the same RMS before rendering.

Azimuth is measured clockwise from straight ahead, so +40° is to the right. A talker at center azimuth \theta_0 that oscillates with amplitude A at rate f follows

\theta(t) = \theta_0 + A \sin\!\big(2\pi (f t + \phi)\big),

so it swings A to either side of \theta_0, 2A from one end to the other. Here f = 2 Hz, as in the experiment, and the start phase \phi decides whether it first moves right (\phi = 0) or left (\phi = 1/2).

Setup, the same on every page
import os
import urllib.request

import matplotlib.pyplot as plt
import numpy as np

import sonore as so

plt.rcParams.update({"font.size": 9, "axes.titlesize": 10, "figure.dpi": 100})


def fetch(path):
    """A file from the sonore repository, by its path there: the local copy when this runs from
    the repository root, otherwise downloaded from GitHub to the same relative path."""
    if not os.path.exists(path):
        os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
        urllib.request.urlretrieve("https://raw.githubusercontent.com/choyun1/sonore/main/" + path, path)
    return path


def finish(snd):
    """How every sound in the gallery is played: 5 ms ramps, RMS 0.1, peak at most 0.95."""
    snd = snd.ramp(5e-3).normalize(rms=0.1)
    return snd.normalize(peak=0.95) if snd.peak > 0.95 else snd
Code
hrirs = so.load_hrirs(distances="all")  # PKU-IOA KEMAR, 20 cm to 1.6 m; downloaded on first use
print(hrirs)

# The sentence, read by each of the two talkers, by the CMU ARCTIC speaker names, at 16 kHz.
SPEAKERS = {"Male talker": "bdl", "Female talker": "slt"}
talkers = {
    label: finish(so.load(fetch(f"docs/speech/{speaker}_arctic_a0131.flac")))
    for label, speaker in SPEAKERS.items()
}
fs = 16000


def excerpt(reader, about):
    """The opening of a LibriSpeech passage, about ``about`` [s] long: from its first sound to
    the quietest 20 ms within 0.4 s of that length, so that it ends between words."""
    snd = so.load(fetch(f"docs/speech/librispeech_{reader}.flac"))
    n = int(20e-3 * fs)
    frames = snd.data[: len(snd) // n * n, 0].reshape(-1, n)
    level = 10 * np.log10(np.mean(frames**2, axis=1) + 1e-20)  # dB, per 20 ms
    first = int(np.argmax(level > level.max() - 30))
    near = first + np.arange(int((about - 0.4) / 20e-3), int((about + 0.4) / 20e-3))
    last = int(near[np.argmin(level[near])])
    return so.Sound(snd.data[first * n : last * n], fs)


MASKERS = {
    "male": [so.load(fetch(f"docs/speech/rms_arctic_{n}.flac")) for n in ("a0132", "a0133")],
    "female": [excerpt("1462_170142", 2.8), excerpt("8842_304647", 4.8)],
}
for sex, recordings in MASKERS.items():
    print(f"{sex} maskers: " + ", ".join(f"{snd.duration:.2f} s" for snd in recordings))

# Equal in RMS, then all padded to the longest, centered in time.
labels, everything = list(talkers), so.normalize([*talkers.values(), *MASKERS["male"], *MASKERS["female"]])
everything = so.match_lengths(everything, align="center")
targets = dict(zip(labels, everything[:2], strict=True))
MASKERS = {"male": everything[2:4], "female": everything[4:6]}
duration = everything[0].duration
TALKING = {
    label: ((duration - snd.duration) / 2, (duration + snd.duration) / 2) for label, snd in talkers.items()
}
CENTERS = (0.0, -40.0, 40.0)  # target ahead, maskers to the left and right [deg]
RATE = 2.0  # oscillations per second


def trajectory(center, amplitude=0.0, phase=0.0):
    """Azimuth over the whole sentence [deg] every 20 ms, for the plots, and the path at 1 m
    that so.move_sound follows, as a function of time."""

    def azimuth(t):
        return center + amplitude * np.sin(2 * np.pi * (RATE * t + phase))

    t = np.arange(0, duration, 0.02)
    return t, azimuth(t), so.hcc_trajectory(100.0, 0.0, azimuth)


LABELS = ("target", "left masker", "right masker")
COLORS = ("#d62728", "#7f7f7f", "#b0b0b0")  # one per talker, in plots and in the view from above


def render(target, amplitude, phase=0.0, maskers=None):
    """The ``target`` talker oscillating with ``amplitude`` [deg] about straight ahead, among
    the ``maskers`` ("male", "female" or None for none), who stand still. Returns the mix, the
    target as rendered on its own, the trajectories' times and each talker's azimuth."""
    t, az_target, path = trajectory(CENTERS[0], amplitude, phase)
    parts = [so.move_sound(targets[target], path, hrirs)]
    azimuths = [az_target]
    for snd, center in zip(MASKERS[maskers] if maskers else [], CENTERS[1:], strict=False):
        _, az, path = trajectory(center)
        parts.append(so.move_sound(snd, path, hrirs))
        azimuths.append(az)
    return so.mix(parts), parts[0], t, azimuths


def scene_of(t, azimuths, labels=LABELS):
    """The talkers for the gallery's view from above, which moves as the sound plays."""
    return [
        {"label": label, "color": color, "t": t, "azimuth": az}
        for az, label, color in zip(azimuths, labels, COLORS, strict=False)
    ]


def draw(where, mix, target_alone, t, azimuths, title, talking, compact=False):
    """Into a figure or subfigure: each talker's azimuth, and the interaural time and level
    differences at the ears, measured in 20 ms windows, of the mix (black) and of the target on
    its own (red). ``talking`` is when the target speaks [s]. Returns the three axes."""
    axes = where.subplots(3, 1, sharex=True)
    for az, label, color in zip(azimuths, LABELS, COLORS, strict=False):
        axes[0].plot(t, az, color=color, lw=1.5, label=label)
    axes[0].axvspan(*talking, color=COLORS[0], alpha=0.08, lw=0, label="target talking")
    axes[0].set(ylim=(-90, 90), yticks=[-80, -40, 0, 40, 80], ylabel="Azimuth [deg]", title=title)
    axes[0].legend(loc="upper right", fontsize=7 if compact else 8, ncols=2 if compact else 4)
    sources = [(mix, "k", "mix")] if len(azimuths) > 1 else []
    for snd, color, label in sources + [(target_alone, COLORS[0], "target alone")]:
        cues = so.interaural_cues(snd, win_dur=20e-3)
        clear = cues.iac > 0.8  # time windows where the two ears are well correlated
        axes[1].plot(cues.t[clear], 1e6 * cues.itd[clear], ".", color=color, ms=2.5, label=label)
        axes[2].plot(cues.t, cues.ild, ".", color=color, ms=2.5, label=label)
    axes[1].set(
        ylim=(-500, 500), ylabel="ITD [µs]", title="Interaural time difference (> 0: right ear first)"
    )
    axes[2].set(
        ylim=(-12, 12), ylabel="ILD [dB]", title="Interaural level difference (> 0: right ear louder)"
    )
    for ax in axes:
        ax.grid(ls=":")
        ax.set_xlim(0, duration)
    for ax in axes[1:]:
        ax.legend(loc="upper right", fontsize=7 if compact else 8, ncols=2, markerscale=3)
    axes[-1].set_xlabel("Time [s]")
    return list(axes)


def show(rendered, title, talking):
    """One talker's demo: ``rendered`` is what render returns."""
    fig = plt.figure(figsize=(10, 6.0), layout="constrained")
    return fig, draw(fig, *rendered, title, talking)


def show_pair(rendered, title, maskers):
    """A column per target talker; ``rendered`` maps each talker's label to what render returns."""
    fig = plt.figure(figsize=(10, 6.6), layout="constrained")
    playhead = {}
    for column, (label, result) in zip(fig.subfigures(1, 2), rendered.items(), strict=True):
        heading = f"{label.split()[0]} target, {maskers} maskers: {title}"
        playhead[label] = draw(column, *result, heading, TALKING[label], compact=True)
    return fig, playhead


def three_talkers(amplitude, phase=0.0, maskers="male", title=""):
    """Both targets, each among the same maskers: the figure, the playhead axes, the sounds and,
    for each target, the talkers seen from above."""
    rendered = {label: render(label, amplitude, phase, maskers) for label in targets}
    fig, playhead = show_pair(rendered, title, maskers)
    sounds = {label: finish(mix) for label, (mix, *_) in rendered.items()}
    scene = {label: scene_of(t, azimuths) for label, (_, _, t, azimuths) in rendered.items()}
    return fig, playhead, sounds, scene
HRIRSet(6344 positions, 1024 taps, 65536 Hz)
male maskers: 2.81 s, 4.82 s
female maskers: 2.62 s, 4.40 s

One talker, moving

Alone, a talker swinging 30° to each side twice a second is easy to hear moving. The motion reaches the ears as interaural differences that change over time: the sound arrives earlier and louder at the ear it moves toward (the cues are measured as on Binaural cues). The cues come from the direction more than from the voice, so one talker is enough here: the female talker. The view from above, beside the example, follows the talker as the sound plays.

One talker, moving 🎧

The female talker alone, swinging 30° to either side of straight ahead at 2 Hz. The interaural time and level differences, measured from the rendered sound in 20 ms windows, follow the azimuth. Time differences are drawn only where the two ears are well correlated.

m1_one_talker_moving.flac, 4.8 s, stereo

Plots of the one talker, moving sound
Code
rendered = render("Female talker", 30.0)
fig, playhead = show(
    rendered, "The female talker alone, swinging 30° to either side", TALKING["Female talker"]
)
scene = scene_of(rendered[2], rendered[3], labels=["female talker"])
sound = finish(rendered[0])

Three talkers

Now the target talks among two maskers. Each demo plays it twice, side by side: on the left the male talker is the target, on the right the female talker, saying the same sentence from the same place among the same maskers. With two male maskers, the male target is one of three similar voices and the female target is the one that differs; with two female maskers it is the other way round. Listeners ignore a masker of the other sex far more easily than one of the same sex (Brungart, 2001, with two talkers at once), so the target should be easier to follow in the right column of the first demo and in the left column of the second. How the two voices differ is measured on What is a voice.

Then the target moves, among the male maskers. Listen for whether motion sets the male target apart from the two male maskers, how far it has to move before it does, and whether it adds anything for the female target, who already differs. In the mix, the interaural differences at any moment come from whichever talker is loudest, so the target's motion shows only in the stretches it dominates.

Three talkers, standing still 🎧

Nobody moves: the target straight ahead, two male maskers 40° to the left and right.

Male talker

m2_three_talkers_standing_still_male_talker.flac, 4.8 s, stereo

Female talker

m2_three_talkers_standing_still_female_talker.flac, 4.8 s, stereo

Plots of the three talkers, standing still sounds
Code
fig, playhead, sounds, scene = three_talkers(0.0, maskers="male", title="nobody moves")

Three talkers, standing still, female maskers 🎧

The same, with two female maskers in place of the male ones.

Male talker

m10_three_talkers_standing_still_female_maskers_male_talker.flac, 4.8 s, stereo

Female talker

m10_three_talkers_standing_still_female_maskers_female_talker.flac, 4.8 s, stereo

Plots of the three talkers, standing still, female maskers sounds
Code
fig, playhead, sounds, scene = three_talkers(0.0, maskers="female", title="nobody moves")

The target swings 10 degrees 🎧

Among the male maskers, the target swings 10° to either side of straight ahead.

Male talker

m3_the_target_swings_10_degrees_male_talker.flac, 4.8 s, stereo

Female talker

m3_the_target_swings_10_degrees_female_talker.flac, 4.8 s, stereo

Plots of the the target swings 10 degrees sounds
Code
fig, playhead, sounds, scene = three_talkers(10.0, maskers="male", title="swings 10°")

The target swings 30 degrees 🎧

The target swings 30° to either side, three quarters of the way to the maskers, starting to the left this time.

Male talker

m4_the_target_swings_30_degrees_male_talker.flac, 4.8 s, stereo

Female talker

m4_the_target_swings_30_degrees_female_talker.flac, 4.8 s, stereo

Plots of the the target swings 30 degrees sounds
Code
fig, playhead, sounds, scene = three_talkers(30.0, phase=0.5, maskers="male", title="swings 30°")

Coming closer

Now a talker walks toward the listener while it says the sentence, from 3 m to 30 cm, 30° to the right; this time it is the male talker. How distance sets the level of the direct sound (the inverse square law) and its ratio to the reverberation of a room is taught with still talkers on Rooms. Here the distance changes while the sentence plays.

Code
WALK = (300.0, 30.0)  # cm: from 3 m to 30 cm
WALK_AZIMUTH = 30.0  # deg, to the right
walker = talkers["Male talker"]  # the sentence without padding
room = so.synth_ir(0.6, fs, n_channels=2, rng=1)  # RT60 0.6 s, a different tail at each ear
print(
    f"{(WALK[0] - WALK[1]) / 100 / walker.duration:.2f} m/s; "
    f"direct sound {so.distance_gain_db(WALK[1] / WALK[0]):+.1f} dB from start to end, "
    f"arriving {1e3 * (WALK[0] - WALK[1]) / 100 / so.SPEED_OF_SOUND:.1f} ms sooner"
)


def walk_in(room=None):
    """The talker walking in while it says the sentence, through all eight measured distances.
    The room, if any, is set so direct and reverberant sound are equal 1 m away."""
    path = so.hcc_trajectory(dist=([0, walker.duration], WALK), elev=0, azim=WALK_AZIMUTH)
    return so.move_sound(walker, path, hrirs, room=room, drr_db=0.0)


def levels_db(data, window=0.2):
    """Level [dB] of each channel of ``data`` (samples, channels) in time windows."""
    n = int(window * fs)
    count = len(data) // n
    power = np.mean(data[: count * n].reshape(count, n, -1) ** 2, axis=1)
    return (np.arange(count) + 0.5) * window, 10 * np.log10(power + 1e-20)


def show_walk(rendered, title):
    """Distance, and the level at each ear re the talker, in 0.2 s time windows."""
    t_walk = np.linspace(0, walker.duration, 200)
    distance = np.interp(t_walk, [0, walker.duration], WALK) / 100
    fig = plt.figure(figsize=(10, 4.5), layout="constrained")
    axes = fig.subplots(2, 1, sharex=True)
    axes[0].plot(t_walk, distance, color=COLORS[0], lw=1.5)
    axes[0].set(ylim=(0, 3.2), ylabel="Distance [m]", title=title)
    t_level, talker_db = levels_db(walker.data)
    ear_db = levels_db(rendered.data)[1][: len(t_level)]
    gain = ear_db - talker_db  # (windows, ears)
    for ear, (label, color) in enumerate([("left ear", "#7f7f7f"), ("right ear", COLORS[0])]):
        axes[1].plot(t_level, gain[:, ear], "o-", color=color, ms=3, lw=1, label=label)
    # 1/r, placed at the right ear's median
    one_over_r = -20 * np.log10(np.interp(t_level, t_walk, distance))
    axes[1].plot(t_level, one_over_r + np.median(gain[:, 1] - one_over_r), "--", color="k", lw=1, label="1/r")
    axes[1].set(ylabel="Level [dB]", title="Level at each ear, re the talker, in 0.2 s windows")
    axes[1].legend(loc="upper left", fontsize=8, ncols=3)
    for ax in axes:
        ax.grid(ls=":")
        ax.set_xlim(0, rendered.duration)
    axes[-1].set_xlabel("Time [s]")
    return fig, list(axes)


def walk_scene():
    t_walk = np.linspace(0, walker.duration, 100)
    return [
        {
            "label": "male talker",
            "color": COLORS[0],
            "t": t_walk,
            "azimuth": np.full_like(t_walk, WALK_AZIMUTH),
            "distance": np.interp(t_walk, [0, walker.duration], WALK) / 100,
        }
    ]
1.07 m/s; direct sound +20.0 dB from start to end, arriving 7.9 ms sooner

Without a room, the direct sound is all there is: it grows as 1/r and arrives sooner as the talker comes in (printed above). Closer than 1.6 m the measured responses (Qu et al., 2009) take over, and the ear on the talker's side gains more than the far ear, so the level difference between the ears grows as the talker comes near. In a room, the reverberation keeps about the same level wherever the talker stands, so the walk turns the sound from mostly room into mostly direct sound.

Walking in 🎧

The male talker walking in from 3 m to 30 cm, with no room. The level at each ear follows 1/r (dashed). The right ear, on the talker's side, is louder throughout, and more so in the last meter.

m5_walking_in.flac, 2.6 s, stereo

Plots of the walking in sound
Code
rendered = walk_in()
fig, playhead = show_walk(rendered, "The male talker walks in, 30° to the right, with no room")
scene = walk_scene()
sound = finish(rendered)

Walking in, in a room 🎧

The same walk in a room with an RT60 of 0.6 s, where direct and reverberant sound are equal at 1 m. Far away the level changes little, because the room sets it; it rises with 1/r only once the direct sound takes over. For the inverse square law and the direct-to-reverberant ratio with a still talker, hear the same sentence four times farther on Rooms.

m6_walking_in_in_a_room.flac, 3.3 s, stereo

Plots of the walking in, in a room sound
Code
rendered = walk_in(room)
fig, playhead = show_walk(rendered, "The same walk in a room (RT60 0.6 s)")
scene = walk_scene()
sound = finish(rendered)

Passing by

A source that changes distance also changes pitch: approaching, each wave starts a little closer than the last and arrives sooner, so the waves are squeezed together, and receding they are stretched apart. Here a 120 Hz buzz passes 3 m in front of the listener, left to right, at 15 m/s (54 km/h). Its pitch is highest while it approaches and falls as it passes, most of the way in the second around the moment of passing; the cell below prints the shift at the start and at the end. Nothing makes the shift happen but the delay changing from sample to sample.

How much listeners use the Doppler shift depends on speed. In the studies reviewed by Carlile & Leung (2016), judgments of a source passing at 10 m/s went with its changes in level and ITD, and Doppler cues dominated only at 50 m/s. Listeners also report the pitch of an approaching source rising, though the Doppler shift holds it steady or lowers it; the rising loudness is what they hear as rising pitch (Neuhoff & McBeath, 1997).

Code
SPEED, CLOSEST, BUZZ_F0 = 15.0, 3.0, 120.0  # m/s, m, Hz
PASS_DURATION = 2.5  # s
buzz = so.harmonic_complex(PASS_DURATION, fs, BUZZ_F0, f_max=5000).normalize()
emitted = (len(buzz) - 1) / fs


def passing(t):
    """Left to right in front of the listener, closest at the middle of the sound."""
    t = np.atleast_1d(t)
    return np.column_stack([SPEED * (t - emitted / 2), np.full_like(t, CLOSEST), np.zeros_like(t)])


t_pass = np.linspace(0, emitted, 250)
distance_pass = np.linalg.norm(passing(t_pass), axis=1)
azimuth_pass = np.mod(so.rect_to_hcc(*passing(t_pass).T)[2] + 180, 360) - 180
# received / emitted frequency = 1 / (1 + (rate of change of distance) / speed of sound)
shift_cents = -1200 * np.log2(1 + np.gradient(distance_pass, t_pass) / so.SPEED_OF_SOUND)
arrival = t_pass + distance_pass / so.SPEED_OF_SOUND
print(f"approaching: {shift_cents[0]:+.0f} cents; receding: {shift_cents[-1]:+.0f} cents")
approaching: +76 cents; receding: -73 cents

Passing by 🎧

A 120 Hz buzz passing 3 m in front at 15 m/s. Its pitch falls by 150 cents in all, about a semitone and a half. The pitch measured at the left ear (dots, by so.f0_track) follows the Doppler shift computed from the path (line).

m7_passing_by.flac, 2.6 s, stereo

Plots of the passing by sound
Code
rendered = so.move_sound(buzz, passing, hrirs)
fig = plt.figure(figsize=(10, 4.5), layout="constrained")
axes = fig.subplots(2, 1, sharex=True)
axes[0].plot(arrival, distance_pass, color=COLORS[0], lw=1.5)
axes[0].set(ylabel="Distance [m]", title="A buzz passing 3 m in front at 15 m/s, as heard")
track = so.f0_track(rendered.left, f_lo=80, f_hi=200)
f0_left = track.f0[0]  # one channel
voiced = f0_left > 0
axes[1].plot(
    track.t[voiced],
    1200 * np.log2(f0_left[voiced] / BUZZ_F0),
    ".",
    color="k",
    ms=3,
    label="measured, left ear",
)
axes[1].plot(arrival, shift_cents, color=COLORS[0], lw=1.5, label="Doppler shift from the path")
axes[1].set(ylim=(-120, 120), ylabel="Pitch re 120 Hz [cents]", title="Pitch at the ear")
axes[1].legend(loc="upper right", fontsize=8)
for ax in axes:
    ax.grid(ls=":")
    ax.set_xlim(0, rendered.duration)
axes[-1].set_xlabel("Time [s]")
playhead = list(axes)
scene = [
    {"label": "buzz", "color": COLORS[0], "t": arrival, "azimuth": azimuth_pass, "distance": distance_pass}
]
sound = finish(rendered)

Straight paths across the plane

The same buzz, at the same 15 m/s, now along six straight lines through different parts of the horizontal plane. The Doppler shift depends only on how fast the distance changes, so every path that passes the listener starts about as sharp as it ends flat. What differs is how quickly the change comes and what the ears hear meanwhile; the cell after the code for the paths measures both.

The buzz stops at 5 kHz (f_max), so that a shift of several semitones up still keeps every harmonic below 8 kHz, half the sampling rate (see A path no source could take).

Code
TOWARD_30 = np.array([np.sin(np.radians(30)), np.cos(np.radians(30))])  # 30° to the right


def straight(point, heading, at=None):
    """A source at ``point`` (x right, y ahead) [m] at time ``at`` (by default the middle of the
    sound), moving along ``heading`` at SPEED: a path as a function of the time it emits."""
    point = np.array([*point, 0.0])
    velocity = SPEED * np.array([*heading, 0.0]) / np.hypot(*heading)
    at = emitted / 2 if at is None else at
    return lambda t: point + np.outer(np.atleast_1d(t) - at, velocity)


PATHS = {
    "Far in front": straight((0, 10), (1, 0)),
    "Close in front": straight((0, 0.5), (1, 0)),
    "Down the right side": straight((1, 0), (0, -1)),
    "Behind": straight((0, -2), (-1, 0)),
    "Crossing at an angle": straight((np.sqrt(0.5), np.sqrt(0.5)), (1, -1)),
    "Straight at the listener": straight(tuple(0.4 * TOWARD_30), tuple(-TOWARD_30), at=emitted),
}
PATH_COLORS = ["#1f77b4", "#d62728", "#2ca02c", "#9467bd", "#ff7f0e", "#8c564b"]


def as_heard(path, n_points=1000):
    """When each point of the path is heard at the head's center [s], and the source's
    distance [m], azimuth [deg, unwrapped] and Doppler shift [cents] then."""
    t = np.linspace(0, emitted, n_points)
    position = path(t)
    distance = np.linalg.norm(position, axis=1)
    azimuth = np.degrees(np.unwrap(np.arctan2(position[:, 0], position[:, 1])))
    cents = -1200 * np.log2(1 + np.gradient(distance, t) / so.SPEED_OF_SOUND)
    return t + distance / so.SPEED_OF_SOUND, distance, azimuth, cents


def show_path(rendered, path, title, color, f0_range=(80, 200), cents_limit=120):
    """Azimuth, the level at each ear with 1/r, and the pitch at the ears against the Doppler
    shift computed from the path, all on the time the sound is heard."""
    arrival, distance, azimuth, cents = as_heard(path)
    fig = plt.figure(figsize=(10, 6.0), layout="constrained")
    axes = fig.subplots(3, 1, sharex=True)
    wrapped = np.mod(azimuth + 180, 360) - 180
    wrapped[1:][np.abs(np.diff(wrapped)) > 180] = np.nan  # no line across ±180°
    axes[0].plot(arrival, wrapped, color=color, lw=1.5)
    axes[0].set(ylim=(-180, 180), yticks=[-180, -90, 0, 90, 180], ylabel="Azimuth [deg]", title=title)
    t_level, ear_db = levels_db(rendered.data, window=0.05)
    for ear, (label, ear_color) in enumerate([("left ear", "#7f7f7f"), ("right ear", "k")]):
        axes[1].plot(t_level, ear_db[:, ear], ".-", color=ear_color, ms=3, lw=0.8, label=label)
    one_over_r = -20 * np.log10(np.interp(t_level, arrival, distance))
    sounding = (t_level > arrival[0] + 0.05) & (t_level < arrival[-1] - 0.05)
    offset = np.median(np.max(ear_db, axis=1)[sounding] - one_over_r[sounding])
    axes[1].plot(
        t_level, np.where(sounding, one_over_r + offset, np.nan), "--", color=color, lw=1.2, label="1/r"
    )
    peak = np.max(ear_db)
    axes[1].set(ylim=(peak - 45, peak + 5), ylabel="Level [dB]", title="Level at each ear, in 50 ms windows")
    axes[1].legend(loc="upper left", fontsize=8, ncols=3)
    for ear, (channel, marker_color) in enumerate([(rendered.left, "#7f7f7f"), (rendered.right, "k")]):
        track = so.f0_track(channel, f_lo=f0_range[0], f_hi=f0_range[1])
        f0_ear = track.f0[0]
        voiced = f0_ear > 0
        axes[2].plot(
            track.t[voiced],
            1200 * np.log2(f0_ear[voiced] / BUZZ_F0),
            ".",
            color=marker_color,
            ms=2.5,
            label=["measured, left ear", "measured, right ear"][ear],
        )
    axes[2].plot(arrival, cents, color=color, lw=1.2, label="Doppler shift from the path")
    axes[2].set(ylim=(-cents_limit, cents_limit), ylabel="Pitch re 120 Hz [cents]", title="Pitch at the ears")
    axes[2].legend(loc="lower left", fontsize=8, ncols=3, markerscale=3)
    for ax in axes:
        ax.grid(ls=":")
        ax.set_xlim(0, rendered.duration)
    axes[-1].set_xlabel("Time [s]")
    return fig, list(axes)


def path_scene(path, label, color):
    arrival, distance, azimuth, _ = as_heard(path, 250)
    return [{"label": label, "color": color, "t": arrival, "azimuth": azimuth, "distance": distance}]


def render_path(number):
    title = list(PATHS)[number]
    path = PATHS[title]
    rendered = so.move_sound(buzz, path, hrirs)
    fig, playhead = show_path(rendered, path, f"{title}, at 15 m/s", PATH_COLORS[number])
    return fig, playhead, path_scene(path, "buzz", PATH_COLORS[number]), finish(rendered)
Code
STATS = {}  # per path, as heard
for title, path in PATHS.items():
    arrival, distance, azimuth, cents = as_heard(path, 20001)
    span = cents[0] - cents[-1]
    # from 95 % to 5 % of the way down (the cents fall, so the arrays are reversed for np.interp)
    t95, t5 = (np.interp(cents[-1] + share * span, cents[::-1], arrival[::-1]) for share in (0.95, 0.05))
    STATS[title] = {
        "closest": distance.min(),
        "start": distance[0],
        "level": 20 * np.log10(distance.max() / distance.min()),
        "sharp": cents[0],
        "flat": cents[-1],
        "glide": t5 - t95 if span > 1 else np.nan,
        "swing": np.ptp(np.interp([-45, 45], azimuth, arrival)) if np.all(np.diff(azimuth) >= 0) else np.nan,
    }
    print(
        f"{title:<25s} closest {distance.min():5.2f} m, level range {STATS[title]['level']:4.1f} dB, "
        f"Doppler {cents[0]:+3.0f} to {cents[-1]:+3.0f} cents, 95 to 5 % of the glide in "
        f"{STATS[title]['glide']:.2f} s"
    )
passing_paths = [title for title in PATHS if STATS[title]["glide"] > 0]
crossing_position = PATHS["Crossing at an angle"](np.linspace(0, emitted, 200001))
crossing_delay = (
    np.argmin(np.abs(crossing_position[:, 1])) - np.argmin(np.linalg.norm(crossing_position, axis=1))
) * (emitted / 200000)
Far in front              closest 10.00 m, level range  6.5 dB, Doppler +68 to -66 cents, 95 to 5 % of the glide in 1.74 s
Close in front            closest  0.50 m, level range 31.5 dB, Doppler +77 to -74 cents, 95 to 5 % of the glide in 0.14 s
Down the right side       closest  1.00 m, level range 25.5 dB, Doppler +77 to -74 cents, 95 to 5 % of the glide in 0.27 s
Behind                    closest  2.00 m, level range 19.5 dB, Doppler +77 to -74 cents, 95 to 5 % of the glide in 0.53 s
Crossing at an angle      closest  1.00 m, level range 25.5 dB, Doppler +77 to -74 cents, 95 to 5 % of the glide in 0.27 s
Straight at the listener  closest  0.40 m, level range 39.5 dB, Doppler +77 to +77 cents, 95 to 5 % of the glide in nan s

Every path that passes the listener starts 68 to 77 cents sharp and ends about as flat. The glide takes longer the farther away the path passes, in proportion at this speed: from 95% to 5% of its range, 0.14 s at 50 cm, 0.27 s at 1 m and 0.53 s at 2 m. The level rises and falls as 1/r, by 6.5 dB on the path 10 m away and 31 dB on the one 50 cm away.

Six straight paths

The six paths seen from above, the listener at the center facing up. Each covers 37.5 m in 2.5 s; the dot marks where it starts.

Six straight paths
Code
fig = plt.figure(figsize=(10, 5.0), layout="constrained")
axes = fig.subplots(1, 2)
for ax, half_width in zip(axes, (20, 3), strict=True):
    for (title, path), color in zip(PATHS.items(), PATH_COLORS, strict=True):
        position = path(np.linspace(0, emitted, 500))
        ax.plot(position[:, 0], position[:, 1], color=color, lw=2, label=title)
        ax.plot(*position[0, :2], "o", color=color, ms=5)
        middle = len(position) // 2 if title != "Straight at the listener" else -60
        ax.annotate(
            "",
            xy=position[middle + 10, :2],
            xytext=position[middle, :2],
            arrowprops={"arrowstyle": "->", "color": color, "lw": 2},
        )
    ax.add_patch(plt.Circle((0, 0), 0.0875, fill=False, color="k"))
    for radius in (1, 1.6, 10):
        ax.add_patch(plt.Circle((0, 0), radius, fill=False, color="0.7", ls=":"))
    ax.set(
        xlim=(-half_width, half_width), ylim=(-half_width, half_width), aspect="equal", xlabel="x, right [m]"
    )
    ax.grid(ls=":", alpha=0.5)
axes[0].set(ylabel="y, ahead [m]", title="From above, 40 m across (circles at 1, 1.6 and 10 m)")
axes[1].set(title="The middle 6 m (the head drawn to scale)")
axes[0].legend(loc="lower left", fontsize=8)

Far in front 🎧

10 m in front, left to right. Far away, the direction changes slowly and the level only by 6.5 dB, and the pitch glides gently over most of two seconds.

ml1_far_in_front.flac, 2.6 s, stereo

Plots of the far in front sound
Code
fig, playhead, scene, sound = render_path(0)

Close in front 🎧

50 cm in front, left to right, inside the measured distances. The level jumps by 31 dB, the azimuth swings from 45° on one side to 45° on the other in 0.07 s, and the pitch drops almost at once.

ml2_close_in_front.flac, 2.6 s, stereo

Plots of the close in front sound
Code
fig, playhead, scene, sound = render_path(1)

Down the right side 🎧

1 m to the right, from front to back. The interaural differences grow as the buzz comes alongside and shrink as it goes behind, just as they would if it turned back the way it came; front and back differ only in the spectral cues of the outer ear, here a KEMAR's, not yours. Once behind, both ears fall a few dB below 1/r, in the shadow of the outer ear.

ml3_down_the_right_side.flac, 2.6 s, stereo

Plots of the down the right side sound
Code
fig, playhead, scene, sound = render_path(2)

Behind 🎧

2 m behind, right to left: the front pass in a mirror. Interaural time and level differences are almost the same for a source in front and behind, so with someone else's ears it may well sound in front.

ml4_behind.flac, 2.6 s, stereo

Plots of the behind sound
Code
fig, playhead, scene, sound = render_path(3)

Crossing at an angle 🎧

From ahead on the left to behind on the right, passing 1 m away 45° to the front right. It crosses the line through the ears 0.07 s after it passes closest.

ml5_crossing_at_an_angle.flac, 2.6 s, stereo

Plots of the crossing at an angle sound
Code
fig, playhead, scene, sound = render_path(4)

Straight at the listener 🎧

Straight at the listener along 30° to the right, from 38 m to 40 cm, where it stops with the sound. The distance shrinks at a steady 15 m/s, so the pitch stays put, 77 cents sharp throughout, while the level climbs by 40 dB. If the pitch seems to rise, that comes from the loudness, as described under Passing by.

ml6_straight_at_the_listener.flac, 2.6 s, stereo

Plots of the straight at the listener sound
Code
fig, playhead, scene, sound = render_path(5)

A path no source could take

Last, a path that is continuous but that nothing in the world could follow. The buzz stays put for 0.1 s, then jumps 60° to 150° around the head and to a new distance between 40 cm and 4 m, in 50 ms, sixteen times over. Each jump follows a quintic "smoothstep" in azimuth and log distance, so position, velocity and acceleration all change without a break; the path is smooth, only absurdly fast.

Code
HOLD, MOVE = 0.10, 0.05  # s: still, then a jump
rng = np.random.default_rng(7)
n_jumps = int(np.ceil(PASS_DURATION / (HOLD + MOVE))) + 1
stops_azimuth, stops_distance = [0.0], [1.0]  # deg, m
for _ in range(n_jumps):
    stops_azimuth.append(stops_azimuth[-1] + rng.choice([-1, 1]) * rng.uniform(60, 150))
    stops_distance.append(np.exp(rng.uniform(np.log(0.4), np.log(4.0))))
stops_azimuth, stops_distance = np.array(stops_azimuth), np.array(stops_distance)


def jumping(t):
    """Distance [m] and azimuth [deg, unwrapped] at times ``t`` [s]."""
    t = np.atleast_1d(np.asarray(t, float))
    jump = np.clip(np.floor(t / (HOLD + MOVE)).astype(int), 0, n_jumps - 1)
    progress = np.clip((t - jump * (HOLD + MOVE) - HOLD) / MOVE, 0, 1)
    weight = progress**3 * (10 - 15 * progress + 6 * progress**2)  # quintic smoothstep
    distance = np.exp(np.log(stops_distance[jump]) * (1 - weight) + np.log(stops_distance[jump + 1]) * weight)
    return distance, stops_azimuth[jump] * (1 - weight) + stops_azimuth[jump + 1] * weight


jumping_path = so.hcc_trajectory(lambda t: 100 * jumping(t)[0], 0.0, lambda t: jumping(t)[1])
t_fine = np.linspace(0, PASS_DURATION, 250001)
velocity = np.gradient(jumping_path(t_fine), t_fine, axis=0)
top_speed = np.linalg.norm(velocity, axis=1).max()
top_acceleration = np.linalg.norm(np.gradient(velocity, t_fine, axis=0), axis=1).max()
jump_starts = np.arange(HOLD, PASS_DURATION, HOLD + MOVE)
longest_jump = np.linalg.norm(jumping_path(jump_starts + MOVE) - jumping_path(jump_starts), axis=1).max()
fastest_turn = np.abs(np.gradient(jumping(t_fine)[1], t_fine)).max() * 5e-3
doppler_range = np.percentile(as_heard(jumping_path, 250001)[3], [0, 100])

Measured on the path:

  • its top speed is 247 m/s, 0.72 of the speed of sound, reached from rest within 25 ms (the buzz passing by above moves at a steady 15 m/s);
  • its acceleration peaks at 1919 g;
  • the longest jump covers 5.5 m in 50 ms, and the fastest turns sweep 28° of azimuth in 5 ms.

The Doppler shift follows the path as faithfully as before: +519 cents (more than four semitones) as the buzz dives in, -556 cents as it leaps out, so here the pitch jumps around as much as the place.

A path no source could take 🎧

The buzz jumping around the head. HRIR shapes are switched every 0.5 ms instead of the usual 5 ms, since a turn of 28° in 5 ms is too coarse a step. The pitch tracker finds the pitch only while the buzz holds still; during the jumps it changes too fast for the tracker's time windows, and the dots stop.

mw1_a_path_no_source_could_take.flac, 2.5 s, stereo

Plots of the a path no source could take sound
Code
rendered = so.move_sound(buzz, jumping_path, hrirs, hop=0.5e-3)
fig, playhead = show_path(
    rendered,
    jumping_path,
    "Still for 0.1 s, then a jump in 50 ms",
    "#d62728",
    f0_range=(60, 250),
    cents_limit=700,
)
scene = path_scene(jumping_path, "buzz", "#d62728")
sound = finish(rendered)

What the renderer does with this, measured by tools/check_moving_trajectories.py (nobody has listened for these artifacts yet):

  • While the buzz holds still, the pitch the tracker finds is the buzz's own, to within 3 cents (95th percentile). During the jumps, where the tracker finds none, the shift was checked on a 1 kHz tone instead: its frequency at each ear follows the shift computed from the distance to that ear to within 7 cents (median) and 43 cents (95th percentile), while the shift itself spans more than ±500 cents. The rest of the difference is not yet explained; the HRIRs' phase, changing with direction, is one candidate.
  • Switching HRIR shapes at the usual 5 ms leaves an error 13 dB below the signal in the worst 20 ms window, against switching every 0.0625 ms; every 0.5 ms, as here, 30 dB below.
  • Nothing aliases, by design: the largest upward shift, a factor of 1.35, takes the top harmonic to 6.6 kHz, below the 8 kHz limit. A buzz with every harmonic up to 8 kHz, which is what so.harmonic_complex makes without f_max, does alias: coming straight at the listener at 15 m/s, its top three harmonics are pushed over the limit and fold back near 7.7–8 kHz, 25 dB below the harmonics.
  • The source comes toward the head at up to 130 m/s here. so.move_sound refuses a source coming at the head faster than sound, whose sound would arrive in reverse order. It renders one at 300 m/s, 0.87 of the speed of sound, and refuses one at 400 m/s.
  • Not modeled at all is the noise a body moving through air that fast would make itself.

How the motion is rendered

A sample the source emits reaches each ear after a delay: the onset of the head-related impulse response at the source's position. PKU-IOA's responses keep the travel time from the source, so at 1.6 m the onset comes 1.7 ms later than at 1 m. so.move_sound follows the path sample by sample: for every output sample and each ear it finds when the sound now arriving was emitted, and reads the source's waveform at that moment, between samples. The delay therefore changes smoothly, and the Doppler shift above comes out of it. What is left of each response once its onset is removed, its shape, is interpolated every 5 ms and cross-faded with raised-cosine windows. Responses between measured directions and distances are interpolated with their onsets aligned and the onsets interpolated separately, which avoids the comb filtering of averaging two responses that arrive at different times; the 3D Tune-In toolkit removes each HRIR's interaural delay before interpolating for the same reason (Cuevas-Rodríguez et al., 2019).

Before, so.move_sound switched whole responses every 5 ms, a smoothed form of a long-standing way to filter with a filter that changes; crossfading the outputs of the old and new filter and swapping parts of a partitioned convolution are the others (Brandtsegg et al., 2018, review all three). That is accurate while the source keeps its distance, as in the swings above. When the distance changes, neighboring responses hold different travel times, and cross-fading two copies of a sound a fraction of a millisecond apart comb-filters it: passing at 15 m/s, copies 5 ms apart in the path differ by 0.2 ms, with the first notch near 2.3 kHz.

References

  • Brandtsegg, Saue & Lazzarini (2018). Live convolution with time-varying filters. Applied Sciences 8(1), 103. MDPI. spatialization.move_sound
  • Brungart (2001). Informational and energetic masking effects in the perception of two simultaneous talkers. J. Acoust. Soc. Am. 109(3), 1101–1109. doi:10.1121/1.1345696.
  • Carlile & Leung (2016). The perception of auditory motion. Trends in Hearing 20. doi:10.1177/2331216516644254.
  • Cho & Kidd (2022). Auditory motion as a cue for source segregation and selection in a "cocktail party" listening environment. J. Acoust. Soc. Am. 152(3), 1684–1694. doi:10.1121/10.0013990. spatialization.move_sound binaural.interaural_cues
  • Cuevas-Rodríguez, Picinali, González-Toledo et al. (2019). 3D Tune-In Toolkit: an open-source library for real-time binaural spatialisation. PLOS ONE 14(3), e0211899. doi:10.1371/journal.pone.0211899. spatialization.HRIRSet
  • Kominek & Black (2004). The CMU Arctic speech databases. Proc. 5th ISCA Speech Synthesis Workshop, 223–224. ISCA Archive. The sentences, by speakers bdl, rms and slt.
  • Neuhoff & McBeath (1997). Overcoming naïve mental models in explaining the Doppler shift: an illusion creates confusion. Am. J. Phys. 65(7), 618–621. PDF.
  • Panayotov, Chen, Povey & Khudanpur (2015). LibriSpeech: an ASR corpus based on public domain audio books. Proc. ICASSP 2015, 5206–5210. doi:10.1109/ICASSP.2015.7178964. The female maskers, cut from two audiobook passages (CC BY 4.0; sources in docs/speech/SOURCES.md).
  • Qu, Xiao, Gong, Huang, Li & Wu (2009). Distance-dependent head-related transfer functions measured with high spatial resolution using a spark gap. IEEE Trans. Audio, Speech, Lang. Process. 17(6), 1124–1132. PKU Scholar. The HRIRs. hrir_data.load_hrirs