commit 65f73020306baa9c756a3edc289a4248645fad3d
parent ddc7b2c1d3d5bd5a2f27650c6579289940ea2429
Author: Jean Schurger <jean@schurger.org>
Date: Sat, 14 Nov 2026 13:47:19 -0500
Alarms heard with the ring/silent switch on silent: bundled tones played through the app's audio session
The leak alarm and the dive computer cues were system sounds, which follow
the ring/silent switch. They are now two synthesized tones bundled in the
app (tools/make-sounds.py: alarm.wav, urgent, for the leak and the dive
alarms; notice.wav, softer, for warnings and safety stop cues), played with
AVAudioPlayer at full player volume. The audio session is "play and record"
on the loudspeaker, set by the app; the capture session no longer
reconfigures it, so that videos keep their sound.
Which cue plays which sound, the silencing by the first button press and
the priority of the leak alarm are in AlertPolicy, with tests.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Diffstat:
8 files changed, 215 insertions(+), 22 deletions(-)
diff --git a/OpenMerou/App/AlertSounds.swift b/OpenMerou/App/AlertSounds.swift
@@ -0,0 +1,76 @@
+// SPDX-License-Identifier: GPL-2.0-only
+// Alert sounds: the leak alarm and the cues of the dive computer. They are played through the app's own
+// audio session and bundled tones (tools/make-sounds.py), not as system sounds, so that they are heard even
+// when the iPhone's ring/silent switch is on silent. The player volume is at its maximum; the volume set
+// with the iPhone's buttons still applies (an app cannot override it).
+@preconcurrency import AVFoundation
+import RemoraDeco
+
+/// The two bundled tones.
+enum AlertSound: String, CaseIterable, Sendable {
+ /// Urgent: leak, dive computer alarm (violation, depth unknown).
+ case alarm
+ /// Softer: dive computer warning, safety stop started or done.
+ case notice
+
+ var url: URL? { Bundle.main.url(forResource: rawValue, withExtension: "wav") }
+}
+
+/// Which sound, if any: pure rules, so that they can be tested.
+/// The leak alarm has priority (no dive sound over it); the first button press silences an alarm.
+enum AlertPolicy {
+ /// Leak alarm, asked every second while the leak lasts.
+ static func leakSound(leaking: Bool, silenced: Bool) -> AlertSound? {
+ leaking && !silenced ? .alarm : nil
+ }
+
+ /// A cue from the dive logic.
+ static func sound(for cue: DiveCue, leaking: Bool, alarmSilenced: Bool) -> AlertSound? {
+ guard !leaking else { return nil }
+ switch cue {
+ case .alarm, .depthLost: return alarmSilenced ? nil : .alarm
+ case .warning, .safetyStopStarted, .safetyStopDone: return .notice
+ case .diveSaved: return nil
+ }
+ }
+}
+
+/// Plays the alert sounds. The audio session is "play and record" on the loudspeaker: that category ignores
+/// the ring/silent switch and lets the camera record the sound of videos at the same time (the capture
+/// session is told not to reconfigure the audio session: see `CameraEngine.configure`).
+@MainActor
+final class AlertPlayer {
+ private var players: [AlertSound: AVAudioPlayer] = [:]
+ /// Last sound asked for (tests, diagnostics).
+ private(set) var lastPlayed: AlertSound?
+
+ /// The category the app wants; `.playback` if the device refuses it (also ignores the switch).
+ static let category = AVAudioSession.Category.playAndRecord
+ static let options: AVAudioSession.CategoryOptions = [.defaultToSpeaker, .mixWithOthers]
+
+ /// To be called once at launch, before the camera starts.
+ func prepare() {
+ let session = AVAudioSession.sharedInstance()
+ do {
+ try session.setCategory(Self.category, mode: .videoRecording, options: Self.options)
+ } catch {
+ try? session.setCategory(.playback, options: [.mixWithOthers])
+ }
+ try? session.setActive(true)
+ for sound in AlertSound.allCases {
+ guard let url = sound.url, let player = try? AVAudioPlayer(contentsOf: url) else { continue }
+ player.volume = 1
+ player.prepareToPlay()
+ players[sound] = player
+ }
+ }
+
+ func play(_ sound: AlertSound) {
+ lastPlayed = sound
+ guard let player = players[sound] else { return }
+ // The session may have been deactivated by an interruption (a phone call).
+ try? AVAudioSession.sharedInstance().setActive(true)
+ player.currentTime = 0
+ player.play()
+ }
+}
diff --git a/OpenMerou/App/AppModel.swift b/OpenMerou/App/AppModel.swift
@@ -1,7 +1,6 @@
// SPDX-License-Identifier: GPL-2.0-only
// Ties the housing to the camera: the buttons that the vacuum sequence leaves free
// drive shooting, the menu and screen sleep.
-import AudioToolbox
import Network
import Observation
import RemoraDeco
@@ -15,6 +14,8 @@ final class AppModel {
/// The optional dive computer, and the basic dive information shown even when it is off.
let dive: DiveSession
@ObservationIgnored let engine = CameraEngine()
+ /// Leak alarm and dive computer sounds: heard even with the ring/silent switch on silent.
+ @ObservationIgnored let alerts = AlertPlayer()
private(set) var camera = CameraState()
private(set) var settings = CameraSettings.load()
private(set) var menu = CameraMenu()
@@ -97,6 +98,7 @@ final class AppModel {
}
camera = state
}
+ alerts.prepare() // the audio session is set before the camera starts
Roll.clearPreviews() // the gallery only shows the current session
engine.start(settings)
exportRoll() // shots left on disk after a crash
@@ -170,26 +172,15 @@ final class AppModel {
}
/// Feedback asked by the dive logic. Haptics are useless in a housing: sounds, and the screen wakes up.
- /// The leak alarm keeps priority: no dive sound over it.
+ /// Which sound is decided by `AlertPolicy` (the leak alarm keeps priority: no dive sound over it).
private func diveCue(_ cue: DiveCue) {
- switch cue {
- case .alarm, .depthLost:
- wakeForDive()
- if !diveAlarmSilenced, !isLeaking { AudioServicesPlayAlertSound(1005) }
- case .warning:
- wakeForDive()
- if !isLeaking { AudioServicesPlayAlertSound(1016) }
- case .safetyStopStarted, .safetyStopDone:
- wakeForDive()
- if !isLeaking { AudioServicesPlaySystemSound(1057) }
- case .diveSaved:
- break
+ if cue != .diveSaved {
+ if sleeping { wake() }
+ lastActivity = Date()
+ }
+ if let sound = AlertPolicy.sound(for: cue, leaking: isLeaking, alarmSilenced: diveAlarmSilenced) {
+ alerts.play(sound)
}
- }
-
- private func wakeForDive() {
- if sleeping { wake() }
- lastActivity = Date()
}
/// Minutes of video that the free space allows, at the chosen quality (approximate HEVC bitrates).
@@ -222,7 +213,7 @@ final class AppModel {
if isLeaking {
if sleeping { wake() }
UIScreen.main.brightness = 1
- if !alarmSilenced { AudioServicesPlayAlertSound(1005) }
+ if let sound = AlertPolicy.leakSound(leaking: true, silenced: alarmSilenced) { alerts.play(sound) }
} else {
alarmSilenced = false
}
diff --git a/OpenMerou/Camera/CameraEngine.swift b/OpenMerou/Camera/CameraEngine.swift
@@ -96,6 +96,9 @@ final class CameraEngine: NSObject, @unchecked Sendable {
return
}
self.device = device
+ // The app sets its audio session itself ("play and record" on the loudspeaker, `AlertPlayer.prepare`)
+ // so that the alarms are heard whatever the ring/silent switch says, while videos keep their sound.
+ session.automaticallyConfiguresApplicationAudioSession = false
session.beginConfiguration()
if session.canAddInput(input) { session.addInput(input) }
if session.canAddOutput(photoOutput) { session.addOutput(photoOutput) }
diff --git a/OpenMerou/Sounds/alarm.wav b/OpenMerou/Sounds/alarm.wav
Binary files differ.
diff --git a/OpenMerou/Sounds/notice.wav b/OpenMerou/Sounds/notice.wav
Binary files differ.
diff --git a/OpenMerouTests/AlertSoundTests.swift b/OpenMerouTests/AlertSoundTests.swift
@@ -0,0 +1,61 @@
+// SPDX-License-Identifier: GPL-2.0-only
+import AVFoundation
+import RemoraDeco
+import Testing
+@testable import OpenMerou
+
+/// Which sound plays when: the rules, and the bundled tones. (That the sound is really heard with the
+/// ring/silent switch on silent can only be checked on an iPhone.)
+struct AlertSoundTests {
+ @Test func leakAlarmSoundsUntilSilenced() {
+ #expect(AlertPolicy.leakSound(leaking: true, silenced: false) == .alarm)
+ #expect(AlertPolicy.leakSound(leaking: true, silenced: true) == nil)
+ #expect(AlertPolicy.leakSound(leaking: false, silenced: false) == nil)
+ }
+
+ @Test func everyCueHasItsSound() {
+ func sound(_ cue: DiveCue) -> AlertSound? { AlertPolicy.sound(for: cue, leaking: false, alarmSilenced: false) }
+ #expect(sound(.alarm) == .alarm)
+ #expect(sound(.depthLost) == .alarm)
+ #expect(sound(.warning) == .notice)
+ #expect(sound(.safetyStopStarted) == .notice)
+ #expect(sound(.safetyStopDone) == .notice)
+ #expect(sound(.diveSaved) == nil)
+ }
+
+ @Test func firstButtonPressSilencesTheAlarmButNotTheNotices() {
+ func sound(_ cue: DiveCue) -> AlertSound? { AlertPolicy.sound(for: cue, leaking: false, alarmSilenced: true) }
+ #expect(sound(.alarm) == nil)
+ #expect(sound(.depthLost) == nil)
+ #expect(sound(.warning) == .notice)
+ #expect(sound(.safetyStopStarted) == .notice)
+ }
+
+ @Test func leakAlarmHasPriorityOverEveryDiveSound() {
+ for cue in DiveCue.allCases {
+ #expect(AlertPolicy.sound(for: cue, leaking: true, alarmSilenced: false) == nil)
+ }
+ }
+
+ @Test func tonesAreBundledAndPlayable() throws {
+ for sound in AlertSound.allCases {
+ let url = try #require(sound.url)
+ let player = try AVAudioPlayer(contentsOf: url)
+ #expect(player.duration > 0.3 && player.duration < 1) // the leak alarm repeats every second
+ }
+ }
+
+ /// The category that ignores the ring/silent switch and still lets the camera record sound.
+ @MainActor @Test func audioSessionIsPlayAndRecordOnTheSpeaker() {
+ #expect(AlertPlayer.category == .playAndRecord)
+ #expect(AlertPlayer.options.contains(.defaultToSpeaker))
+ }
+
+ @MainActor @Test func playerRemembersWhatItWasAskedToPlay() {
+ let player = AlertPlayer()
+ player.prepare()
+ #expect(player.lastPlayed == nil)
+ player.play(.notice)
+ #expect(player.lastPlayed == .notice)
+ }
+}
diff --git a/README.md b/README.md
@@ -35,7 +35,8 @@ validated underwater yet.
or the stop to do. A long press up, or Menu → Dive computer, opens a full-screen page (left goes back).
The settings can be read in Menu → Information, not changed.
- Alarms flash the whole screen red with a sound and wake the screen; the first button press silences the
- sound. The leak alarm keeps priority.
+ sound. The leak alarm keeps priority. The sounds are the app's own tones (`tools/make-sounds.py`), played
+ even when the ring/silent switch is on silent; the volume of the iPhone still applies.
- Real dives are handed over to the Sub Rascasse logbook: see [docs/SHARING.md](docs/SHARING.md).
- The basic dive information is written in the metadata of the photos and videos taken during a dive, whether
the computer is on or off (see docs/SHARING.md).
@@ -65,7 +66,8 @@ For the dive computer: `-diveComputer YES -acceptTerms` (on for this launch), `-
`-noPermissionPrompts` (screenshots in the simulator). In the simulated housing, "Simulate a dive" does the
same by touch.
-Tools: `tools/pklg.py` decodes an iOS Bluetooth log (PacketLogger, sysdiagnose).
+Tools: `tools/pklg.py` decodes an iOS Bluetooth log (PacketLogger, sysdiagnose); `tools/make-sounds.py`
+generates the alert tones of `OpenMerou/Sounds`.
## License
diff --git a/tools/make-sounds.py b/tools/make-sounds.py
@@ -0,0 +1,60 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-2.0-only
+"""Generates the alert sounds bundled in the app (OpenMerou/Sounds): plain synthesized tones, so that no
+third-party recording is involved.
+
+Usage: tools/make-sounds.py [output directory]
+
+- alarm.wav: urgent, three quick two-tone beeps (leak alarm, dive computer alarms);
+- notice.wav: softer, two rising notes (dive computer warnings, safety stop cues).
+
+The frequencies sit where a phone loudspeaker is loudest (2 to 3 kHz for the alarm).
+"""
+import math
+import struct
+import sys
+import wave
+
+RATE = 22_050
+
+
+def tone(frequency, seconds, level, harmonics=()):
+ """A sine (plus optional odd harmonics for a harsher sound) with 5 ms fades to avoid clicks."""
+ count = int(RATE * seconds)
+ fade = int(RATE * 0.005)
+ out = []
+ for i in range(count):
+ t = i / RATE
+ value = math.sin(2 * math.pi * frequency * t)
+ for order, weight in harmonics:
+ value += weight * math.sin(2 * math.pi * frequency * order * t)
+ envelope = min(1.0, i / fade, (count - 1 - i) / fade)
+ out.append(level * envelope * value / (1 + sum(w for _, w in harmonics)))
+ return out
+
+
+def silence(seconds):
+ return [0.0] * int(RATE * seconds)
+
+
+def write(path, samples):
+ with wave.open(path, "wb") as f:
+ f.setnchannels(1)
+ f.setsampwidth(2)
+ f.setframerate(RATE)
+ f.writeframes(b"".join(struct.pack("<h", int(max(-1.0, min(1.0, s)) * 32767)) for s in samples))
+
+
+def main():
+ out = sys.argv[1] if len(sys.argv) > 1 else "OpenMerou/Sounds"
+ harsh = ((3, 0.33), (5, 0.2))
+ alarm = []
+ for _ in range(3):
+ alarm += tone(2_400, 0.11, 0.95, harsh) + tone(3_000, 0.11, 0.95, harsh) + silence(0.05)
+ write(f"{out}/alarm.wav", alarm)
+ notice = tone(1_320, 0.14, 0.7) + silence(0.05) + tone(1_760, 0.2, 0.7)
+ write(f"{out}/notice.wav", notice)
+
+
+if __name__ == "__main__":
+ main()