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