Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

The end of a rest or a hold chimes louder, in a high-low-high pattern no other sound uses (Discord: rest timer sound too quiet)

Duarte Santoscf04c962d891
diff --git a/frontend/src/lib/sound.js b/frontend/src/lib/sound.js
index 6f7ceefd8..9724ab934 100644
--- a/frontend/src/lib/sound.js
+++ b/frontend/src/lib/sound.js
@@ -47,20 +47,60 @@ const sleepAfter = endSec => {
}, at - Date.now())
}
+// A timbre brighter than a sine: the fundamental plus three falling harmonics. It carries over
+// music and through a phone speaker's weak low end without a square wave's buzz. The browser
+// normalises a periodic wave to a peak of 1, so the gain alone decides how loud it gets. Built
+// once per context; a browser without createPeriodicWave gets the nearest built-in shape.
+let brightWave = null
+let brightCtx = null
+const setBright = (ctx, o) => {
+ if (typeof ctx.createPeriodicWave !== 'function') { o.type = 'triangle'; return }
+ if (brightCtx !== ctx) {
+ brightCtx = ctx
+ brightWave = ctx.createPeriodicWave(new Float32Array([0, 0, 0, 0, 0]), new Float32Array([0, 1, 0.6, 0.35, 0.2]))
+ }
+ o.setPeriodicWave(brightWave)
+}
+
+// One tone. The defaults are every beep the app has always made: a sine that reaches 0.35 and
+// fades from there at once. `peak`, `hold` (the share of the tone kept at its peak before the
+// fade) and `bright` exist for the timer chime below.
+const tone = (freq, dur, when, { peak = 0.35, hold = 0, bright = false } = {}) => {
+ const ctx = wake()
+ const o = ctx.createOscillator(), g = ctx.createGain()
+ o.connect(g); g.connect(ctx.destination)
+ o.frequency.value = freq
+ if (bright) setBright(ctx, o); else o.type = 'sine'
+ const t0 = ctx.currentTime + when
+ g.gain.setValueAtTime(0.001, t0)
+ g.gain.exponentialRampToValueAtTime(peak, t0 + 0.02)
+ if (hold > 0) g.gain.setValueAtTime(peak, t0 + dur * hold)
+ g.gain.exponentialRampToValueAtTime(0.001, t0 + dur)
+ o.start(t0); o.stop(t0 + dur + 0.05)
+ sleepAfter(when + dur + 0.05)
+}
+
export function beep(enabled, freq, dur, when) {
if (!enabled) return
- try {
- const ctx = wake()
- const o = ctx.createOscillator(), g = ctx.createGain()
- o.connect(g); g.connect(ctx.destination)
- o.frequency.value = freq || 880; o.type = 'sine'
- const t0 = ctx.currentTime + (when || 0)
- g.gain.setValueAtTime(0.001, t0)
- g.gain.exponentialRampToValueAtTime(0.35, t0 + 0.02)
- g.gain.exponentialRampToValueAtTime(0.001, t0 + (dur || 0.18))
- o.start(t0); o.stop(t0 + (dur || 0.18) + 0.05)
- sleepAfter((when || 0) + (dur || 0.18) + 0.05)
- } catch (e) { /* */ }
+ try { tone(freq || 880, dur || 0.18, when || 0) } catch (e) { /* */ }
+}
+
+// The end of a rest or a hold (store/useUI.js). It used to be three of the beeps above and went
+// unheard under music (Discord: "Rest Timer Sound Notification too Quiet"): an exponential fade
+// from 0.35 is down to a tenth of that before the tone is half over. So this one
+// - peaks at CHIME_PEAK instead of 0.35. The output clips above 1, and the notes are spaced so
+// that each has stopped before the next starts, so they never add up past the peak;
+// - holds that peak for most of each note instead of fading from the first millisecond;
+// - uses the brighter timbre;
+// - has a shape of its own, high, low, then high and long (E6 B5 E6), that neither the 3-2-1
+// ticks before it (660 Hz), a set tick (1040 Hz) nor the rising finish fanfare has.
+// It does not turn other apps down. A web page cannot duck another app's audio: Android only
+// grants audio focus to native code, and on iOS the 'playback' session pauses the music (1. above).
+export const CHIME_PEAK = 0.9
+const CHIME = [[1319, 0.16, 0], [988, 0.16, 0.22], [1319, 0.5, 0.44]]
+export function chime(enabled) {
+ if (!enabled) return
+ try { CHIME.forEach(([freq, dur, when]) => tone(freq, dur, when, { peak: CHIME_PEAK, hold: 0.6, bright: true })) } catch (e) { /* */ }
}
// Call from inside a tap. Gets the context created and running while the browser still counts
diff --git a/frontend/src/lib/sound.test.js b/frontend/src/lib/sound.test.js
index c19f7144e..7c97446d9 100644
--- a/frontend/src/lib/sound.test.js
+++ b/frontend/src/lib/sound.test.js
@@ -11,16 +11,33 @@ class FakeCtx {
this.tones = []
this.resumes = 0
this.suspends = 0
+ this.gains = []
+ this.oscs = []
+ this.waves = 0
FakeCtx.instances.push(this)
}
resume() { this.resumes++; this.state = 'running'; return Promise.resolve() }
suspend() { this.suspends++; this.state = 'suspended'; return Promise.resolve() }
- createGain() { return { connect() {}, gain: { setValueAtTime() {}, exponentialRampToValueAtTime() {} } } }
+ // Each gain remembers what it was asked to do, so the chime's loudness can be read back.
+ createGain() {
+ const events = []
+ this.gains.push(events)
+ return { connect() {}, gain: {
+ setValueAtTime(v, at) { events.push(['set', v, at]) },
+ exponentialRampToValueAtTime(v, at) { events.push(['ramp', v, at]) },
+ } }
+ }
createOscillator() {
const ctx = this
- const o = { frequency: { value: 0 }, type: '', connect() {}, start(at) { ctx.tones.push({ freq: o.frequency.value, at }) }, stop() {} }
+ const o = {
+ frequency: { value: 0 }, type: '', wave: null, connect() {},
+ setPeriodicWave(w) { o.wave = w },
+ start(at) { ctx.tones.push({ freq: o.frequency.value, at }); ctx.oscs.push(o); o.at = at },
+ stop(at) { o.until = at },
+ }
return o
}
+ createPeriodicWave(real, imag) { this.waves++; return { real: [...real], imag: [...imag] } }
}
FakeCtx.instances = []
@@ -196,3 +213,79 @@ describe('play on silent (Settings switch, WebKit only)', () => {
expect(() => sound.setPlayOnSilent(true)).not.toThrow()
})
})
+
+// Discord, "Rest Timer Sound Notification too Quiet": the end of a rest has to carry over music.
+describe('the chime at the end of a rest or a hold', () => {
+ const peakOf = events => Math.max(...events.map(([, v]) => v))
+
+ it('makes no sound and no context with sounds off', () => {
+ sound.chime(false)
+ expect(FakeCtx.instances).toHaveLength(0)
+ })
+
+ it('is high, low, high: none of the pitches of the countdown, a set tick or the finish fanfare', () => {
+ sound.chime(true)
+ const freqs = ctx().tones.map(tn => tn.freq)
+ expect(freqs).toHaveLength(3)
+ expect(freqs[0]).toBeGreaterThan(freqs[1])
+ expect(freqs[2]).toBe(freqs[0])
+ for (const other of [660, 1040, 880, 1100, 1320]) expect(freqs).not.toContain(other)
+ })
+
+ it('peaks well above a beep and below the point where the output clips', () => {
+ sound.beep(true, 660, 0.1)
+ const beepPeak = peakOf(ctx().gains[0])
+ sound.chime(true)
+ const chimePeaks = ctx().gains.slice(1).map(peakOf)
+ expect(beepPeak).toBe(0.35)
+ for (const p of chimePeaks) {
+ expect(p).toBe(sound.CHIME_PEAK)
+ expect(p).toBeGreaterThan(beepPeak * 2)
+ expect(p).toBeLessThanOrEqual(1)
+ }
+ })
+
+ it('never has two notes sounding at once, so they cannot add up past the peak', () => {
+ sound.chime(true)
+ const notes = ctx().oscs
+ for (let i = 1; i < notes.length; i++) expect(notes[i].at).toBeGreaterThanOrEqual(notes[i - 1].until)
+ })
+
+ it('holds its peak for most of each note instead of fading from the start', () => {
+ sound.chime(true)
+ const first = ctx().gains[0]
+ const held = first.find(([kind, v, at]) => kind === 'set' && v === sound.CHIME_PEAK && at > 0.05)
+ expect(held).toBeTruthy()
+ })
+
+ it('uses one brighter periodic wave for all its notes', () => {
+ sound.chime(true)
+ expect(ctx().waves).toBe(1)
+ expect(ctx().oscs.every(o => o.wave && o.wave.imag.filter(Boolean).length > 1)).toBe(true)
+ })
+
+ it('falls back to a triangle wave without createPeriodicWave', async () => {
+ class NoWaveCtx extends FakeCtx {}
+ NoWaveCtx.prototype.createPeriodicWave = undefined
+ window.AudioContext = NoWaveCtx
+ vi.resetModules()
+ sound = await import('./sound.js')
+ sound.chime(true)
+ expect(ctx().oscs.map(o => o.type)).toEqual(['triangle', 'triangle', 'triangle'])
+ })
+
+ it('leaves the plain beeps a sine at their old level', () => {
+ sound.beep(true, 1040, 0.12)
+ expect(ctx().oscs[0].type).toBe('sine')
+ expect(ctx().oscs[0].wave).toBeNull()
+ })
+
+ it('lets the context sleep once its last note is over', () => {
+ sound.chime(true) // the last note ends at 0.44 + 0.5 + 0.05 = 0.99s
+ vi.advanceTimersByTime(1900)
+ expect(ctx().state).toBe('running')
+ vi.advanceTimersByTime(200)
+ expect(ctx().state).toBe('suspended')
+ })
+})
+
diff --git a/frontend/src/store/useUI.js b/frontend/src/store/useUI.js
index 01e1fc70f..d343cd9e2 100644
--- a/frontend/src/store/useUI.js
+++ b/frontend/src/store/useUI.js
@@ -1,6 +1,6 @@
import { create } from 'zustand'
import { uid } from '../lib/format.js'
-import { beep, vibrate } from '../lib/sound.js'
+import { beep, chime, vibrate } from '../lib/sound.js'
import { api } from '../lib/api.js'
import { t } from '../lib/i18n.js'
import { deviceId } from '../lib/push.js'
@@ -105,7 +105,7 @@ export const useUI = create((set, get) => ({
const snd = useStore.getState().S.sound
if (left <= 0) {
if (seenLive) {
- beep(snd, 880, 0.15); beep(snd, 880, 0.15, 0.25); beep(snd, 1320, 0.4, 0.5)
+ chime(snd)
vibrate([200, 100, 200]); get().flashTimer()
}
// The toast stays even when the rest ran out while the app was hidden: a guest, or anyone
@@ -169,7 +169,7 @@ export const useUI = create((set, get) => ({
const snd = useStore.getState().S.sound
if (left <= 0) {
if (seenLive) {
- beep(snd, 880, 0.15); beep(snd, 880, 0.15, 0.25); beep(snd, 1320, 0.4, 0.5)
+ chime(snd)
vibrate([200, 100, 200]); get().flashTimer()
}
const done = workDone