Code
from scipy.signal import butter, sosfilt
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 = 44100
# the recordings are at 16 kHz; the rooms are built at 44.1 kHz
sentences = {label: snd.resample(FS) for label, snd in talkers.items()}
def starter_pistol():
"""A sharp broadband crack: a shock-like pulse (0.15 ms exponential), highpassed.
Its spectrum is smooth; a short burst of noise would have random deep notches."""
t = np.arange(int(0.03 * FS)) / FS
x = sosfilt(butter(2, 300, "highpass", fs=FS, output="sos"), np.exp(-t / 0.15e-3))
return so.Sound(x, FS).pad(before=0.05, after=0.05)
def room(**kw):
"""A synthetic room: RT60 1 s, direct-to-reverberant ratio -3 dB, a fixed seed."""
return so.synth_ir(1.0, FS, drr_db=-3, rng=5, **kw)
def drr_db(ir):
"""The direct-to-reverberant ratio of an IR [dB]: its first sample's energy over the rest's."""
return 10 * np.log10(ir.data[0, 0] ** 2 / np.sum(ir.data[1:, 0] ** 2))
def level_db(ir, t, window=0.05):
"""The level of an IR's tail [dB] in a 50 ms window starting at time t, relative to its
first 50 ms."""
tail = ir.data[1:, 0] ** 2
n, k = int(window * ir.fs), int(t * ir.fs)
return 10 * np.log10(tail[k : k + n].mean() / tail[:n].mean())
def share_above(snd, f=4000):
"""The fraction of a sound's energy above f [Hz]."""
power = np.abs(np.fft.rfft(snd.data[:, 0])) ** 2
return power[np.fft.rfftfreq(len(snd), 1 / snd.fs) > f].sum() / power.sum()
def show_sound(snd, ax_wave, ax_coch, title=""):
"""Waveform and cochleagram (60 dB range) of a sound."""
snd.plot(ax_wave, color="k", lw=0.4)
ax_wave.set(title=title or "Waveform", xlabel="", ylabel="")
# no extra lowpass: resampling to 1 kHz is already band-limited, and a
# lowpass would ring visibly around the sharp onset of the shot
cochleagram = so.cosine_filterbank(30, 50, 8000).analyze(snd).envelopes(fs=1000)
cochleagram.plot(ax_coch, colorbar=False, db_range=60)
ax_coch.set_title("Cochleagram (60 dB range)")
for ax in (ax_wave, ax_coch):
ax.set_xlim(0, snd.duration)
def show_room(ax_decay, ax_rt60, ir, kw=None):
"""The IR's decay in four bands, and its RT60s by band against those of natural rooms."""
tail = so.Sound(ir.data[1:], ir.fs)
env = so.cosine_filterbank(30, 50, 8000).analyze(tail).envelopes(lowpass=30, fs=1000)
for f, color in zip(
(125, 500, 2000, 6000), ("tab:blue", "tab:green", "tab:orange", "tab:red"), strict=True
):
k = int(np.argmin(np.abs(env.cfs - f)))
db = env.db[:, k, 0]
ax_decay.plot(env.t, db - db.max(), color=color, lw=0.8, label=f"{env.cfs[k]:.0f} Hz")
ax_decay.set(
ylim=(-70, 3), xlabel="Time [s]", ylabel="Band envelope [dB]", title="The IR's decay in four bands"
)
# a time-reversed decay rises to the upper right, so its legend goes on the left
reversed_decay = (kw or {}).get("decay_shape") == "time_reversed"
ax_decay.legend(fontsize=8, loc="upper left" if reversed_decay else "upper right")
ax_decay.grid(ls=":")
# measured RT60 profile vs the ecological one
cfs, rt = so.measure_rt60(tail)
ax_rt60.plot(
cfs,
so.band_rt60s(1.0, cfs, profile="ecological"),
color="k",
lw=1.2,
ls="--",
label="natural rooms (RT60 = 1 s)",
)
profile = (kw or {}).get("rt60_profile")
if profile:
# requested profile, computed over synth_ir's own bands (which run to 16 kHz)
synth_cfs = so.cosine_filterbank(32, 20, min(16000, FS / 2)).cfs
requested = np.interp(cfs, synth_cfs, so.band_rt60s(1.0, synth_cfs, profile=profile))
ax_rt60.plot(cfs, requested, color="tab:purple", lw=1, ls=":", label=f"requested ({profile})")
if not kw or "decay_shape" not in kw:
ax_rt60.plot(cfs, rt, color="tab:purple", lw=1.2, marker=".", label="this IR (measured)")
else:
ax_rt60.text(
0.03,
0.06,
"decay isn't exponential, so an RT60\nisn't meaningful for this IR",
transform=ax_rt60.transAxes,
fontsize=8,
)
so.plotting.log_frequency_axis(ax_rt60, "x")
ax_rt60.set(xlabel="Frequency [Hz]", ylabel="RT60 [s]", title="Decay time by frequency", ylim=(0, 1.8))
ax_rt60.legend(fontsize=8, loc="upper right")
ax_rt60.grid(ls=":", which="both")
def show(snd, ir, kw=None):
"""One sound: waveform and cochleagram, then the IR's decay by band and its RT60s.
Returns the figure and the panels the playhead follows."""
fig, axes = plt.subplots(2, 2, figsize=(10, 6.2), layout="constrained")
show_sound(snd, axes[0, 0], axes[0, 1])
if ir is None:
for ax in axes[1]:
ax.axis("off")
axes[1, 0].text(0.0, 0.5, "No room: the dry source.", transform=axes[1, 0].transAxes, fontsize=11)
else:
show_room(axes[1, 0], axes[1, 1], ir, kw)
return fig, [axes[0, 0], axes[0, 1]]
def show_pair(sounds, ir, kw=None, panels=show_room):
"""One column per talker (waveform and cochleagram), and below them the room both are in,
drawn by `panels` in two axes. Returns the figure and, for each talker, the panels the
playhead follows."""
fig = plt.figure(figsize=(10, 8.4), layout="constrained")
top, bottom = fig.subfigures(2, 1, height_ratios=[1.25, 1])
playhead = {}
for column, (label, snd) in zip(top.subfigures(1, 2), sounds.items(), strict=True):
ax_wave, ax_coch = column.subplots(2, 1, sharex=True, height_ratios=[0.45, 1])
show_sound(snd, ax_wave, ax_coch, label)
playhead[label] = [ax_wave, ax_coch]
panels(*bottom.subplots(1, 2), ir, kw)
return fig, playhead
pistol = starter_pistol()