v0.67.1: the air horn is one continuous tone

The old recording was a two-note phrase that wobbled 9% in pitch, so no
loop of it could hold a tone. A steady CC0 can (guitarguy1985, 359-361 Hz
for 7 s) replaces it: held, it plays on and laps a long crossfade; a click
is at least half a second; letting go bends the pitch down as it fades.
This commit is contained in:
2026-10-17 22:57:26 -07:00
parent 056f794e86
commit 8e39335988
7 changed files with 182 additions and 168 deletions
+15 -14
View File
@@ -417,8 +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`): a tap plays the
phrase, holding loops its first blast. The zoomed lanes ease out ×2
(`sounds/airhorn.mp3`, CC0, see `sounds/CREDITS.md`; Round 98 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.
@@ -433,18 +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 97, the third go — measure before touching it): the
recording's first blast wobbles in pitch and loudness on a ~0.15 s
cycle, so a loop cut against that cycle *is* a repeating beat. Held, it
loops exactly one cycle (`Horn.LOOP` 0.0779 s + 0.1494 s, the best
self-similarity, corr 0.81), levelled (envelope divided out: min/max
0.74 → 0.88) and crossfaded equal-power; a press is a fresh blast and
cuts any still sounding in 25 ms (taps stay separate); a release, after
at least `MIN_BLAST` 0.18 s, crossfades into the recording's own ending
(`TAIL` 0.42–0.60 s: the pitch drop and fade) — a click is a 0.37 s BWAH
that trails off. `render` works in pieces that stop at each state change,
so a block's size never changes the sound. test_round97 holds all of it
to numbers (no step bigger than the recording's own, held swing > 0.7).
**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.
**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.0"
__version__ = "0.67.1"
+86 -114
View File
@@ -261,34 +261,34 @@ def crossfade_gains(x: float) -> tuple[float, float]:
class Horn:
"""The air horn, played like a sampler plays a held instrument (Round
97 — the third go; see ``set_sample`` for the measurements).
"""The air horn: one continuous tone for as long as it's held.
The recording ("Air Horn Hype", CC0 — lintunes/sounds/CREDITS.md)
has a first blast whose pitch and loudness wobble on a ~0.15 s cycle,
then a natural ending: the pitch drops and it fades, 0.42–0.60 s.
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.
- **press**: a fresh blast from the top. A blast still sounding is
cut with a quick fade (``CUT``), so rapid taps are separate BWAHs,
never a smear.
- **held**: the blast carries on — one natural wobble cycle (``LOOP``,
found by self-similarity: the start and length where the waveform
best matches itself a lap later), looped with an equal-power
crossfade, so it neither jumps nor repeats a beat.
- **release**: after at least ``MIN_BLAST`` of blast (a click still
says BWAH), it crossfades into the recording's own ending (``TAIL``)
and stops there — the trail-off, never a hard cut and never the
rest of the phrase.
- **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".
"""
LOOP = (0.0779, 0.1494) # start, length (s) — best self-match, corr 0.81
TAIL = (0.42, 0.60) # the blast's own ending: pitch drop and fade
MIN_BLAST = 0.18 # a click still gets this much blast
XFADE = 0.04 # the loop seam, equal power
TAIL_XFADE = 0.025 # into the ending
CUT = 0.025 # a retriggered blast's fade
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)
CUT = 0.025
VOICES = 4
LEVEL = 1.0
LEVEL = 0.9
def __init__(self, sample: np.ndarray | None = None):
self.on = False
@@ -302,43 +302,36 @@ class Horn:
src = sample.astype(np.float32)
if sample.dtype == np.int16:
src /= 32768.0
peak = float(np.abs(src).max()) or 1.0
n = len(src)
a = int(self.LOOP[0] * RATE)
length = int(self.LOOP[1] * RATE)
self._loop = (a, min(n, a + length))
# Held, that one cycle repeats — and its own loudness wobble (min/
# max 0.74 across the cycle) repeated twenty times a held second
# reads as a pulse. So the cycle is levelled (to 0.88): its smooth
# envelope divided out, the gain itself smoothed so nothing zips.
# Only the looped stretch changes; attack and ending are untouched.
mono = src.mean(axis=1)
win = int(0.015 * RATE)
env = np.sqrt(np.convolve(mono * mono, np.ones(win) / win, mode="same"))
lo, hi = max(0, a - int(self.XFADE * RATE)), self._loop[1]
gain = np.ones(n, np.float32)
gain[lo:hi] = np.clip(env[lo:hi].mean() / np.maximum(env[lo:hi], 1e-6), 0.6, 1.6)
k = int(0.01 * RATE)
gain = np.convolve(gain, np.ones(k) / k, mode="same").astype(np.float32)
self._src = src * gain[:, None]
t0, t1 = (min(n, int(t * RATE)) for t in self.TAIL)
self._tail = (t0, t1)
# The ending fades out over its last 60 % so it lands on silence.
tail = src[t0:t1].copy()
fade = np.ones(len(tail), np.float32)
k = int(len(tail) * 0.4)
fade[k:] = np.cos(np.linspace(0, np.pi / 2, len(tail) - k)) ** 2
self._tail_audio = tail * fade[:, None]
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
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:
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)
# ---- 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["gain"] = 1.0
self._voices.append({"state": "held", "pos": 0, "gain": 1.0,
"tail_pos": 0, "xfade": 0})
voice["fade"] = 0
self._voices.append({"state": "held", "pos": float(int(self.ONSET * RATE)),
"started": 0, "gain": 1.0, "rate": 1.0, "fade": 0})
del self._voices[:-self.VOICES]
def release(self):
@@ -349,87 +342,66 @@ class Horn:
# ---- sound ----
def _blast(self, pos: int, count: int) -> tuple[np.ndarray, int]:
"""``count`` frames of held blast from ``pos``: the recording, with
the loop's seam crossfaded (equal power) as it laps."""
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."""
a, b = self._loop
out = np.empty((count, CHANNELS), np.float32)
xf = int(self.XFADE * RATE)
idx = pos + np.arange(count)
steps = pos + np.concatenate([[0.0], np.cumsum(rates[:-1])])
if b > a:
over = idx >= b
idx[over] = a + (idx[over] - a) % (b - a)
out[:] = self._src[np.minimum(idx, len(self._src) - 1)]
# within xf before the seam, fade the end out and what precedes the
# start in — so the lap lands on the start seamlessly
near = (idx >= b - xf) & (idx < b)
if near.any() and a >= xf:
t = (idx[near] - (b - xf)) / xf
out[near] = (self._src[idx[near]] * np.cos(t * np.pi / 2)[:, None]
+ self._src[idx[near] - (b - a)] * np.sin(t * np.pi / 2)[:, None])
return out, int(idx[-1]) + 1
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)
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))
kept = []
for voice in self._voices:
done = 0
alive = True
# In pieces that stop where the voice changes state (the end of
# the minimum blast, the end of its ending), so a big block is
# as exact as a small one.
while done < count and alive:
n, alive = self._voice(voice, out, done, count - done)
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":
n = min(room, cut - voice["fade"])
frames, voice["pos"] = self._read(voice["pos"], np.ones(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]
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)
self._voices = kept
return out * self.LEVEL
def _voice(self, voice: dict, out: np.ndarray, at: int, room: int) -> tuple[int, bool]:
"""Render up to ``room`` frames of ``voice`` into ``out[at:]``;
returns (frames rendered, still sounding)."""
state = voice["state"]
min_blast = int(self.MIN_BLAST * RATE)
if state == "releasing" and voice["pos"] >= min_blast:
state = voice["state"] = "tail"
voice["xfade"] = 0
voice["tail_pos"] = 0
if state in ("held", "cut") or state == "releasing":
n = room
if state == "releasing":
n = max(1, min(room, min_blast - voice["pos"]))
frames, voice["pos"] = self._blast(voice["pos"], n)
if state == "cut":
step = 1.0 / (self.CUT * RATE)
gain = np.clip(voice["gain"] - step * np.arange(1, n + 1), 0, 1)
voice["gain"] = float(gain[-1])
frames *= gain[:, None]
out[at:at + n] += frames
return n, voice["gain"] > 0
out[at:at + n] += frames
return n, True
# the ending: crossfade from the blast into the recording's own tail
tail = self._tail_audio
start = voice["tail_pos"]
n = min(room, len(tail) - start)
if n <= 0:
return 0, False
frames = tail[start:start + n].copy()
txf = int(self.TAIL_XFADE * RATE)
done = voice["xfade"]
if done < txf:
blast, voice["pos"] = self._blast(voice["pos"], n)
t = np.clip((np.arange(n) + done) / txf, 0, 1)
frames = (blast * np.cos(t * np.pi / 2)[:, None]
+ frames * np.sin(t * np.pi / 2)[:, None])
voice["xfade"] = done + n
out[at:at + n] += frames
voice["tail_pos"] = start + n
return n, voice["tail_pos"] < len(tail)
class Mixer:
def __init__(self):
+7 -4
View File
@@ -1,7 +1,10 @@
# Sound credits
- `tink.wav` — LinTunes' own.
- `airhorn.mp3` — "Air Horn Hype" by zar.265 on Freesound
(https://freesound.org/people/zar.265/sounds/581334/), released under
Creative Commons 0 (public domain). The DJ shelf's air horn plays its
first blast, sustained for as long as the button is held.
- `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.)
Binary file not shown.
+1 -35
View File
@@ -44,41 +44,7 @@ def _envelope(mono, seconds=0.015):
return np.sqrt(np.convolve(mono * mono, np.ones(win) / win, mode="same"))
class TestHorn:
def test_a_click_is_a_short_blast_that_trails_off(self, recording):
x, _ = _play(recording, [("press", 0.01), ("release", 0.0)])
assert 0.3 < len(x) / RATE < 0.45
env = _envelope(x)
assert env[-int(0.02 * RATE):].max() < 0.05 * env.max() # fades to nothing
# …gradually: the last 120 ms fall, they don't drop off a cliff
tail = env[-int(0.12 * RATE):]
assert tail[0] > 4 * tail[-1]
def test_a_hold_sustains_without_clicks_or_a_beat(self, recording):
x, _ = _play(recording, [("press", 3.0), ("release", 0.0)])
source = recording.astype(np.float32).mean(axis=1) / 32768
own_step = np.abs(np.diff(source[:int(0.6 * RATE)])).max()
assert np.abs(np.diff(x)).max() <= own_step + 1e-3 # no seam clicks
held = _envelope(x)[int(0.6 * RATE):int(2.6 * RATE)]
assert held.min() / held.max() > 0.7 # steady, no pulse
assert len(x) / RATE < 3.0 + 0.45 # stops on release
def test_taps_stay_separate_then_a_hold_carries(self, recording):
x, horn = _play(recording, [("press", 0.06), ("release", 0.12)] * 6
+ [("press", 2.5), ("release", 0.0)])
held = _envelope(x)[int(1.6 * RATE):int(3.2 * RATE)]
assert held.min() / held.max() > 0.7
assert not horn._voices
def test_a_retrigger_cuts_the_old_blast_quickly(self, recording):
horn = Horn(recording)
horn.press()
horn.render(4410)
horn.press()
states = [v["state"] for v in horn._voices]
assert states == ["cut", "held"]
horn.render(int(0.03 * RATE))
assert [v["state"] for v in horn._voices] == ["held"]
# The horn's tests moved to test_round98 with its new recording.
class TestLoops:
+72
View File
@@ -0,0 +1,72 @@
"""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"]