v0.67.2: the air horn is the classic rap horn

trav's recording from instantrapairhorn.com replaces the steady can. A
click plays the whole blast untouched; held, it laps the steady stretch
through a crossfade matched to the recording's own loudness; let go after
a lap, it jumps straight to the recording's own ending.
This commit is contained in:
2026-10-19 00:25:53 -07:00
parent 8e39335988
commit 2e5ebf0b0b
7 changed files with 222 additions and 175 deletions
+15 -15
View File
@@ -417,7 +417,7 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal
"Synced", until its own tempo fader moves; only one deck follows; the
½×/1×/2× switch re-syncs a synced pair (`sync_ratio` folds any number of
octaves). |◀ per deck. The air horn is a real recording
(`sounds/airhorn.mp3`, CC0, see `sounds/CREDITS.md`; Round 98 below). The zoomed lanes ease out ×2
(`sounds/airhorn.mp3`, see `sounds/CREDITS.md`; Round 99 below). The zoomed lanes ease out ×2
while a deck is paused or held. The sink reopens when the system's
default output changes (`output._Pump`: `audioOutputsChanged`, a device
id check, an error check) — it used to go silent until DJ mode reopened.
@@ -432,20 +432,20 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal
both waveforms. **Sync sets once** (trav's call): it puts this deck at the
other's tempo and stays lit only while that holds (`_check_sync`: same
song on the other deck, tempos still equal) — nothing follows anything.
**The horn** (Round 98, the fourth go — the first three failed on the
*recording*, not the code: "Air Horn Hype" is a two-note phrase whose
pitch wanders 9 %, so any loop of it is a beat and any click a
"bee-doop"). Now `sounds/airhorn.mp3` is guitarguy1985's steady can
(359–361 Hz for 7 s, CC0). Held, it simply plays on and laps
`Horn.LOOP` (1.0–7.3 s) through a 0.3 s equal-power crossfade baked into
the sample; a press is a fresh blast from `ONSET` and cuts any still
sounding in 25 ms; a release, after at least `MIN_BLAST` 0.5 s, fades
over `RELEASE` 0.3 s while the read rate falls to `BEND` 0.94 — the
"-ew" (a click ≈ 0.8 s). `render` works in pieces that stop at each
state change. test_round98 holds it to numbers (pitch within 2 % for
12 s held and after taps, no seam step bigger than the recording's own).
**Before swapping the recording, measure its pitch track** — a steady
sample is the whole design.
**The horn** (Round 99, the fifth go — trav chose the sound: the
classic rap horn from instantrapairhorn.com, `sounds/airhorn.mp3`). It is
one blast: a swoop ~420 → 305 Hz in its first 0.35 s, then 302 Hz steady
to 1.62 s, then its own short end. A click plays the whole recording
untouched, as that page does. Held, it laps `Horn.LOOP` (0.729–1.450 s)
through a 0.2 s crossfade baked into a copy (`_laps`); the steady part is
beating reeds, not a repeating wave (seams correlate ~0.3 at best), so
the crossfade is equal loudness *for the measured correlation*. Let go
before a lap, it plays out; after one, it jumps (40 ms, matched to the
nearest wave cycle) to the loop end, so the ending follows at once. A
press cuts a blast still sounding in 25 ms. test_round99 holds it to the
recording's own loudness range. **Before changing the recording, measure
its pitch and loudness track** — Rounds 93–98 failed on the recording,
not the code.
**Loops** (Round 97, djay's Quantize behaviour): a loop starts on the
*nearest* beat (it may be just behind — playback carries on inside it);
under a beat, it snaps to its own grid; resizing keeps the start and
+1 -1
View File
@@ -1,3 +1,3 @@
"""LinTunes — iTunes-style music library manager and player for Linux."""
__version__ = "0.67.1"
__version__ = "0.67.2"
+112 -79
View File
@@ -261,34 +261,31 @@ def crossfade_gains(x: float) -> tuple[float, float]:
class Horn:
"""The air horn: one continuous tone for as long as it's held.
"""The air horn: the classic rap horn, one continuous blast.
The recording ("airhorn.wav" by guitarguy1985, CC0 —
lintunes/sounds/CREDITS.md) is a real canned horn: a quarter-second
swell gliding down into the note, then one steady tone (359–361 Hz,
within 0.5 %) for seven seconds. Measured, because the one before it
("Air Horn Hype", Rounds 93–97) was a two-note phrase that wobbled 9 %
— no amount of looping could make it hold a tone.
The recording (``sounds/airhorn.mp3``, trav's pick — see
lintunes/sounds/CREDITS.md) is one blast: a swoop from ~420 Hz down to
~305 Hz over its first 0.35 s ("BWAAA"), then one steady tone (302 Hz,
within 1 %) until 1.62 s and a short natural end.
- **press**: a fresh blast from its attack; one still sounding is cut
in ``CUT`` (rapid taps stay separate blasts).
- **held**: the recording plays on; past ``LOOP``'s end it laps back to
its start, a long equal-power crossfade apart — inaudible on a tone
this steady.
- **release**: after at least ``MIN_BLAST`` (a click is a real blast,
not a blip), the tone falls ``BEND`` in pitch while fading over
``RELEASE`` — a can running out of air: the "-ew" of "bweeeew".
- **click**: the whole recording, as on the web page it came from.
- **held**: past ``LOOP``'s end it laps back to its start through a
``XFADE`` crossfade. The steady part is reeds beating, not a
repeating wave (seams correlate ~0.3 at best), so the crossfade is
equal *loudness* for that correlation, measured in ``set_sample``.
- **release**: a blast that never lapped plays out naturally; one that
did jumps (``JUMP``, matched to the nearest wave cycle) to the loop
end, so the recording's own ending follows at once.
- **press** again: a fresh blast; one still sounding is cut in ``CUT``.
"""
ONSET = 0.04 # s: where the swell starts in the file
LOOP = (1.0, 7.3) # s: the steady stretch it laps within
XFADE = 0.30 # s: the lap's crossfade
MIN_BLAST = 0.50 # s: what a click always gets
RELEASE = 0.30 # s: the fade on letting go…
BEND = 0.94 # …while the pitch falls to this (~1 semitone)
ONSET = 0.14 # s: just before the blast starts in the file
LOOP = (0.729, 1.450) # s: the steady stretch it laps within
XFADE = 0.20 # s: the lap's crossfade
JUMP = 0.04 # s: release → the ending
CUT = 0.025
VOICES = 4
LEVEL = 0.9
LEVEL = 1.0
def __init__(self, sample: np.ndarray | None = None):
self.on = False
@@ -302,69 +299,99 @@ class Horn:
src = sample.astype(np.float32)
if sample.dtype == np.int16:
src /= 32768.0
peak = float(np.abs(src).max()) or 1.0
src /= float(np.abs(src).max()) or 1.0
n = len(src)
a, b = (min(n - 1, int(t * RATE)) for t in self.LOOP)
if b - a < RATE // 2: # some other, shorter sound: lap its middle
if b - a < RATE // 4: # some other, shorter sound: lap its middle
a, b = n // 4, n - n // 20
xf = min(int(self.XFADE * RATE), max(1, (b - a) // 2))
# The lap's seam baked in: the stretch's last xf frames fade from
# themselves into what comes before its start, so b → a lands on a
# continuation (equal power — the tone is steady, so they agree).
looped = src.copy()
if a >= xf:
xf = min(int(self.XFADE * RATE), (b - a) // 2, a)
# The lap's seam, baked into a copy: the stretch's last xf frames
# fade from themselves into what comes before its start, so b → a
# lands on a continuation. Scaled for the two sides' correlation,
# so the seam is neither a dip nor a swell.
laps = src.copy()
if xf > 0:
tail, head = src[b - xf:b], src[a - xf:a]
corr = float((tail * head).sum()
/ (np.sqrt((tail * tail).sum() * (head * head).sum()) or 1.0))
t = np.linspace(0, 1, xf, dtype=np.float32)[:, None]
looped[b - xf:b] = (src[b - xf:b] * np.cos(t * np.pi / 2)
+ src[a - xf:a] * np.sin(t * np.pi / 2))
self._src = looped / peak
self._loop = (a, b)
fo, fi = np.cos(t * np.pi / 2), np.sin(t * np.pi / 2)
laps[b - xf:b] = (tail * fo + head * fi) / np.sqrt(1 + 2 * corr * fo * fi)
self._src, self._laps, self._loop = src, laps, (a, b)
self._onset = min(int(self.ONSET * RATE), a)
# ---- the button ----
def press(self):
self.on = True
for voice in self._voices:
if voice["state"] == "ending": # cut from where its fade is
k = voice["fade"] / max(1, int(self.RELEASE * RATE))
voice["gain"] = float(np.cos(k * np.pi / 2) ** 2)
if voice["state"] != "cut":
voice["state"] = "cut"
voice["fade"] = 0
self._voices.append({"state": "held", "pos": float(int(self.ONSET * RATE)),
"started": 0, "gain": 1.0, "rate": 1.0, "fade": 0})
voice.update(state="cut", fade=0)
self._voices.append({"state": "held", "pos": self._onset,
"lapped": False, "fade": 0})
del self._voices[:-self.VOICES]
def release(self):
self.on = False
if self._src is None:
return
a, b = self._loop
xf = min(int(self.XFADE * RATE), (b - a) // 2, a)
for voice in self._voices:
if voice["state"] == "held":
voice["state"] = "releasing"
if voice["state"] != "held":
continue
if voice["lapped"]:
voice.update(state="jump", fade=0, to=self._match(voice["pos"], b))
elif voice["pos"] >= b - xf: # mid-seam: back onto the original
voice.update(state="jump", fade=0, to=voice["pos"])
else:
voice["state"] = "free"
def _match(self, pos: int, near: int) -> int:
"""Where around ``near`` the original best continues what the
held voice is playing at ``pos`` (within one wave cycle)."""
win = int(self.JUMP * RATE)
here = self._laps[pos:pos + win, 0]
best, at = -2.0, near
for to in range(max(0, near - 160), min(len(self._src) - win, near + 160)):
there = self._src[to:to + win, 0]
c = float((here * there).sum())
if c > best:
best, at = c, to
return at
# ---- sound ----
def _read(self, pos: float, rates: np.ndarray) -> tuple[np.ndarray, float]:
"""Frames from ``pos`` at the given per-frame rates (1 = as
recorded), lapping within the loop; linear interpolation."""
def _read(self, voice: dict, n: int, source: np.ndarray) -> np.ndarray:
"""n frames from the voice's position; a held voice laps."""
pos = voice["pos"]
if voice["state"] == "held":
a, b = self._loop
steps = pos + np.concatenate([[0.0], np.cumsum(rates[:-1])])
if b > a:
over = steps >= b
steps[over] = a + (steps[over] - a) % (b - a)
i0 = np.minimum(steps.astype(np.int64), len(self._src) - 2)
frac = (steps - i0)[:, None].astype(np.float32)
frames = self._src[i0] * (1 - frac) + self._src[i0 + 1] * frac
end = steps[-1] + rates[-1]
if b > a and end >= b:
end = a + (end - a) % (b - a)
return frames, float(end)
out = np.empty((n, CHANNELS), np.float32)
done = 0
while done < n:
take = min(n - done, b - pos)
out[done:done + take] = source[pos:pos + take]
done += take
pos += take
if pos >= b:
pos = a
voice["lapped"] = True
voice["pos"] = pos
return out
frames = source[pos:pos + n]
voice["pos"] = pos + len(frames)
if len(frames) < n:
frames = np.concatenate([frames, np.zeros((n - len(frames), CHANNELS), np.float32)])
return frames
def render(self, count: int) -> np.ndarray | None:
if self._src is None or not self._voices:
return None
out = np.zeros((count, CHANNELS), np.float32)
min_blast = int(self.MIN_BLAST * RATE)
release = int(self.RELEASE * RATE)
cut = max(1, int(self.CUT * RATE))
jump = max(1, int(self.JUMP * RATE))
end = len(self._src)
kept = []
for voice in self._voices:
done = 0
@@ -372,30 +399,36 @@ class Horn:
while done < count and alive:
room = count - done
state = voice["state"]
if state == "releasing" and voice["started"] >= min_blast:
state = voice["state"] = "ending"
if state in ("held", "releasing"):
n = room if state == "held" else max(1, min(room, min_blast - voice["started"]))
frames, voice["pos"] = self._read(voice["pos"], np.ones(n))
out[done:done + n] += frames
voice["started"] += n
elif state == "cut":
if state == "held":
n = room
out[done:] += self._read(voice, n, self._laps)
elif state == "free":
n = min(room, end - voice["pos"])
out[done:done + n] += self._read(voice, n, self._src)
alive = voice["pos"] < end
elif state == "jump": # held sound out, the ending in
n = min(room, jump - voice["fade"])
k = (voice["fade"] + np.arange(n)) / jump
old = self._laps[voice["pos"]:voice["pos"] + n]
new = self._src[voice["to"]:voice["to"] + n]
m = min(len(old), len(new))
out[done:done + m] += (old[:m] * np.cos(k[:m, None] * np.pi / 2)
+ new[:m] * np.sin(k[:m, None] * np.pi / 2))
voice["pos"] += n
voice["to"] += n
voice["fade"] += n
if voice["fade"] >= jump:
voice.update(state="free", pos=voice["to"])
if m < n:
alive = False
else: # cut
n = min(room, cut - voice["fade"])
frames, voice["pos"] = self._read(voice["pos"], np.ones(n))
pos = min(voice["pos"], end - n)
k = voice["fade"] + np.arange(1, n + 1)
gain = voice["gain"] * np.clip(1 - k / cut, 0, 1)
out[done:done + n] += frames * gain[:, None]
out[done:done + n] += self._laps[pos:pos + n] * np.clip(1 - k / cut, 0, 1)[:, None]
voice["pos"] = pos + n
voice["fade"] += n
alive = voice["fade"] < cut
else: # ending: fade out while the pitch falls
n = min(room, release - voice["fade"])
k = (voice["fade"] + np.arange(n)) / release
rates = 1.0 - (1.0 - self.BEND) * k
frames, voice["pos"] = self._read(voice["pos"], rates)
gain = np.cos(k * np.pi / 2) ** 2
out[done:done + n] += frames * gain[:, None]
voice["fade"] += n
alive = voice["fade"] < release
done += n
if alive:
kept.append(voice)
+7 -7
View File
@@ -1,10 +1,10 @@
# Sound credits
- `tink.wav` — LinTunes' own.
- `airhorn.mp3` — "airhorn.wav" by guitarguy1985 on Freesound
(https://freesound.org/people/guitarguy1985/sounds/64476/), released
under Creative Commons 0 (public domain). Trimmed to its attack and its
steady blast (0.40–8.00 s of the original). The DJ shelf's air horn
plays it for as long as the button is held.
- (Round 93–97 used "Air Horn Hype" by zar.265, also CC0 — but it is a
two-note phrase that wobbles, so it could never hold one tone.)
- `airhorn.mp3` — the classic rap air horn as played by
https://www.instantrapairhorn.com/, added by trav as-is (1.72 s, 22 kHz
mp3). Its licence isn't stated there.
- Earlier horns, both CC0 from Freesound and both dropped: "Air Horn Hype"
by zar.265 (Rounds 93–97, a wobbling two-note phrase) and "airhorn.wav"
by guitarguy1985 (Round 98, a steady can that didn't sound like the
rap horn).
Binary file not shown.
-72
View File
@@ -1,72 +0,0 @@
"""Round 98: the air horn is one continuous tone. A steady recording
(guitarguy1985, CC0) replaces the two-note "Hype" one; held, it plays on
and laps a long crossfade; a click is a real blast; letting go bends the
pitch down as it fades ("bweeeew"); taps are separate blasts."""
import numpy as np
import pytest
from lintunes.dj.audio import RATE, Horn
from lintunes.dj.loader import decode
from tests.test_round97 import _envelope, _play
@pytest.fixture(scope="module")
def recording():
from importlib import resources
with resources.as_file(resources.files("lintunes") / "sounds" / "airhorn.mp3") as path:
return decode(str(path))
def _pitches(x, start, stop, window=4096):
"""The strongest frequency (250–450 Hz) in each window."""
found = []
for i in range(int(start * RATE), int(stop * RATE) - window, window // 2):
spectrum = np.abs(np.fft.rfft(x[i:i + window] * np.hanning(window), window * 8))
freqs = np.fft.rfftfreq(window * 8, 1 / RATE)
band = (freqs > 250) & (freqs < 450)
found.append(freqs[band][spectrum[band].argmax()])
return np.array(found)
class TestHorn:
def test_a_held_horn_is_one_tone_past_the_recording(self, recording):
x, horn = _play(recording, [("press", 12.0), ("release", 0.0)])
pitch = _pitches(x, 0.4, 11.9)
assert pitch.max() / pitch.min() < 1.02 # one note
held = _envelope(x, 0.05)[int(0.4 * RATE):int(11.9 * RATE)]
assert held.min() / held.max() > 0.5 # never drops out
source = recording.astype(np.float32).mean(axis=1) / 32768
own_step = np.abs(np.diff(source)).max() / np.abs(source).max()
assert np.abs(np.diff(x)).max() <= own_step * horn.LEVEL + 1e-3 # no seam clicks
assert not horn._voices
def test_a_click_is_a_real_blast_that_bends_down(self, recording):
x, _ = _play(recording, [("press", 0.05), ("release", 0.0)])
assert 0.7 < len(x) / RATE < 0.9
pitch = _pitches(x, 0.1, 0.45)
assert pitch.max() / pitch.min() < 1.03 # no "bee-doop"
assert _pitches(x, 0.6, 0.75).mean() < pitch.mean() * 0.98 # the "-ew"
env = _envelope(x)
assert env[-int(0.02 * RATE):].max() < 0.05 * env.max()
def test_taps_then_a_hold_carry_one_tone(self, recording):
x, horn = _play(recording, [("press", 0.06), ("release", 0.12)] * 6
+ [("press", 4.0), ("release", 0.0)])
start = 6 * 0.18 + 0.4
pitch = _pitches(x, start, start + 3.4)
assert pitch.max() / pitch.min() < 1.02
held = _envelope(x, 0.05)[int(start * RATE):int((start + 3.4) * RATE)]
assert held.min() / held.max() > 0.5
assert not horn._voices
def test_a_retrigger_cuts_the_old_blast_quickly(self, recording):
horn = Horn(recording)
horn.press()
horn.render(4410)
horn.release()
horn.render(RATE // 2) # now fading out
horn.press()
assert [v["state"] for v in horn._voices] == ["cut", "held"]
horn.render(int(0.03 * RATE))
assert [v["state"] for v in horn._voices] == ["held"]
+86
View File
@@ -0,0 +1,86 @@
"""Round 99: the classic rap air horn (trav's recording, from
instantrapairhorn.com). A click plays the whole blast as that page does;
held, it laps its steady stretch at the recording's own loudness; let go
after a lap, it goes straight to the recording's own ending; taps are
separate blasts. (Round 98's steady-can recording and its tests are gone.)"""
import numpy as np
import pytest
from lintunes.dj.audio import RATE, Horn
from lintunes.dj.loader import decode
from tests.test_round97 import _play
@pytest.fixture(scope="module")
def recording():
from importlib import resources
with resources.as_file(resources.files("lintunes") / "sounds" / "airhorn.mp3") as path:
return decode(str(path))
def _loudness(x, start, stop, window=0.05):
w = int(window * RATE)
return np.array([np.sqrt((x[i:i + w] ** 2).mean())
for i in range(int(start * RATE), int(stop * RATE) - w, w)])
def _pitches(x, start, stop, window=4096):
"""The fundamental (250–350 Hz) in each window."""
found = []
for i in range(int(start * RATE), int(stop * RATE) - window, window // 2):
spectrum = np.abs(np.fft.rfft(x[i:i + window] * np.hanning(window), window * 8))
freqs = np.fft.rfftfreq(window * 8, 1 / RATE)
band = (freqs > 250) & (freqs < 350)
found.append(freqs[band][spectrum[band].argmax()])
return np.array(found)
def _own(horn):
"""The recording's steady stretch: its own loudness range."""
a, b = (t / RATE for t in horn._loop)
return _loudness(horn._src.mean(axis=1), a, b)
class TestHorn:
def test_a_click_plays_the_whole_blast_untouched(self, recording):
x, horn = _play(recording, [("press", 0.01), ("release", 0.0)])
whole = horn._src[horn._onset:].mean(axis=1)
assert len(x) >= len(whole)
np.testing.assert_allclose(x[:len(whole)], whole, atol=1e-6)
assert not horn._voices
def test_a_hold_is_one_steady_blast_then_its_own_ending(self, recording):
x, horn = _play(recording, [("press", 6.0), ("release", 0.0)])
own = _own(horn)
held = _loudness(x, 0.7, 5.9)
assert held.min() > 0.9 * own.min() and held.max() < 1.1 * own.max()
pitch = _pitches(x, 0.7, 5.9)
assert pitch.max() / pitch.min() < 1.03 # one note
assert len(x) / RATE < 6.0 + 0.4 # ends at once
source = horn._src.mean(axis=1)
assert np.abs(np.diff(x)).max() <= np.abs(np.diff(source)).max() + 0.02
def test_letting_go_before_a_lap_plays_out_naturally(self, recording):
x, horn = _play(recording, [("press", 0.8), ("release", 0.0)])
whole = horn._src[horn._onset:].mean(axis=1)
np.testing.assert_allclose(x[:len(whole)], whole, atol=1e-6)
def test_taps_then_a_hold_carry_one_blast(self, recording):
x, horn = _play(recording, [("press", 0.06), ("release", 0.12)] * 6
+ [("press", 4.0), ("release", 0.0)])
start = 6 * 0.18 + 0.6
held = _loudness(x, start, start + 3.3)
own = _own(horn)
assert held.min() > 0.9 * own.min() and held.max() < 1.1 * own.max()
assert not horn._voices
def test_a_retrigger_cuts_the_old_blast_quickly(self, recording):
horn = Horn(recording)
horn.press()
horn.render(4410)
horn.release()
horn.press()
assert [v["state"] for v in horn._voices] == ["cut", "held"]
horn.render(int(0.03 * RATE))
assert [v["state"] for v in horn._voices] == ["held"]