From 1d7310c0cd89cef7d502640d614a9147dea13bef Mon Sep 17 00:00:00 2001 From: Himanshu Kapoor Date: Sat, 28 Nov 2026 12:16:52 +0100 Subject: [PATCH 1/3] PlatformAudio: the music comes back after the app returns, and follows only the game's music switch The soundtrack no longer steps aside for other apps' audio (`stepsAsideForOtherAudio`, iOS's secondary-audio hint, Android's isMusicActive check), which misjudged what was playing and, once it stepped aside, often never came back. iOS: an ambient session (mixes with other apps, never interrupted by their playback, silenced by the Ring/Silent switch). The soundtrack picks up on didBecomeActive with the session reactivated, rather than on willEnterForeground while the app is still in the background, so it also comes back after an interruption that never says it ended (Siri, a declined call). Interruptions told late for a suspended app are ignored. Android: the game takes audio focus each time it comes back from a stop while its music is on (Android keeps an app that lost focus muted until it asks again), and holds none while music is off. Focus asked during a call is granted as it ends. AndroidPlatformServices.Audio replaces audioFocusChanged; AudioManager.audioFocusDidChange(interrupted:) replaces audioFocusDidChange(otherAudio:interrupted:). --- AGENTS.md | 4 +- .../spritekit/platform/AudioFocusPolicy.java | 52 +++++++------ .../spritekit/platform/DeviceServices.java | 76 ++++++++++++------- .../platform/AudioFocusPolicyTest.java | 68 ++++++++++++----- .../AndroidPlatformServices.swift | 33 ++++++-- .../PlatformAndroidHost/ToolkitServices.swift | 15 +++- .../PlatformAudio/AppleAudioBackend.swift | 63 +++++++++------ .../PlatformAudio/AudioConfiguration.swift | 5 -- .../Sources/PlatformAudio/AudioManager.swift | 46 +++++------ .../PlatformAndroidHostTests.swift | 4 +- .../PlatformAndroidTests.swift | 15 +++- .../AudioManagerTests.swift | 26 ++++--- README.md | 12 ++- Templates/App/README.md | 2 +- 14 files changed, 267 insertions(+), 154 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 14d4dd1e..5aafbf41 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -180,8 +180,8 @@ would want. a copy of the capture scripts. - Scenes play sounds and music with `PlatformAudio`'s `playSound`, `playMusic` and `stopMusic`, never a game's own wrappers of them. -- Keep `AudioManager`'s default of pausing the music while another app plays - audio (`stepsAsideForOtherAudio`); no game turns it off. +- The soundtrack follows only the game's own music switch: no game silences + it for other apps' audio, which mixes in on Apple platforms. - A game's soundtrack plays its intro once and then repeats a loop on the beat: its masters stay out of the bundle, and the runtime's `Tools/Audio/music.js` (its README), through the game's own two-line diff --git a/Library/spritekit/src/main/java/com/spritekit/platform/AudioFocusPolicy.java b/Library/spritekit/src/main/java/com/spritekit/platform/AudioFocusPolicy.java index 769a3a09..7e77c104 100644 --- a/Library/spritekit/src/main/java/com/spritekit/platform/AudioFocusPolicy.java +++ b/Library/spritekit/src/main/java/com/spritekit/platform/AudioFocusPolicy.java @@ -1,43 +1,51 @@ package com.spritekit.platform; /** - * When the game asks for audio focus, apart from Android so a unit test can - * drive it ({@code AudioFocusPolicyTest}). + * When the game asks for audio focus and gives it up, apart from Android so + * a unit test can drive it ({@code AudioFocusPolicyTest}). * - *

The game tells another app's music by {@code AudioManager.isMusicActive()}, - * which counts every app's stream, the game's own included. That reads true - * only for others when the game's stream is stopped, which it is as the game - * first starts and after a stop (SDL pauses it as the surface goes). A pause - * without a stop (a dialog or the shade's device controls over the game, a - * second launch intent, Play's sign-in) leaves it playing. So the game keeps - * its focus through such a pause, gives it up only when it stops, and looks - * for other music only as it comes back from a stop. Asking on every resume - * once took the game's own soundtrack for another app's and kept it quiet - * until the next time the app went to the background. + *

The game's soundtrack follows its own music switch alone. While the + * switch is on, the game asks for focus each time it comes back from a stop + * (and as it first starts), whatever another app is playing: Android fades + * out an app that lost focus and keeps it muted until it asks again, so a + * game that didn't ask would come back silent. Through a pause without a + * stop (a dialog or the shade's device controls over the game, a second + * launch intent, Play's sign-in) it keeps what it has: if the player + * started their own music meanwhile, it plays until the game next comes + * back. While the switch is off, the game holds no focus, so the player's + * own music plays on under the game's sounds. */ final class AudioFocusPolicy { - /** What a resume does about focus. */ + /** What to do about focus. */ enum Step { - /** Nothing has changed that the game can see: keep what it has. */ KEEP, - /** Ask for focus (the soundtrack plays once it's granted). */ REQUEST, - /** Another app's music is playing: no focus, the soundtrack quiet. */ - OTHER_AUDIO, + ABANDON, } - /** Whether the game's stream is stopped: before the first start, and after a stop. */ + /** Whether the game is stopped: before the first start, and after a stop. */ private boolean stopped = true; + /** The game's music switch: null until the game says. */ + private Boolean wanted; - Step onResume(boolean holdsFocus, boolean musicActive) { + Step onResume(boolean holdsFocus) { boolean afterStop = stopped; stopped = false; - if (holdsFocus || !afterStop) return Step.KEEP; - return musicActive ? Step.OTHER_AUDIO : Step.REQUEST; + return afterStop && !holdsFocus && Boolean.TRUE.equals(wanted) ? Step.REQUEST : Step.KEEP; } - /** The game went to the background: give focus up. */ + /** The game went to the background: it gives focus up. */ void onStop() { stopped = true; } + + /** The game says whether it wants focus (its music switch). */ + Step onWanted(boolean wanted, boolean holdsFocus) { + boolean changed = this.wanted == null || this.wanted != wanted; + this.wanted = wanted; + if (!changed || stopped) return Step.KEEP; + if (wanted && !holdsFocus) return Step.REQUEST; + if (!wanted && holdsFocus) return Step.ABANDON; + return Step.KEEP; + } } diff --git a/Library/spritekit/src/main/java/com/spritekit/platform/DeviceServices.java b/Library/spritekit/src/main/java/com/spritekit/platform/DeviceServices.java index 4d8f304b..b6a0fea9 100644 --- a/Library/spritekit/src/main/java/com/spritekit/platform/DeviceServices.java +++ b/Library/spritekit/src/main/java/com/spritekit/platform/DeviceServices.java @@ -42,13 +42,13 @@ * and a short buzz on the oldest. Played as touch feedback, so the system's * own "vibration & haptics" switch silences them as it does every app's. * - *

Audio focus, to the iOS build's ambient session: the player's - * own music wins. If something else is playing music as the game comes to - * the front, the game asks for no focus and keeps its soundtrack quiet - * (its sounds still mix in); otherwise it takes focus for the soundtrack and - * steps aside the moment another app takes it, and pauses for a call. It - * holds focus until it stops, not merely pauses ({@link AudioFocusPolicy}). - * Events: {@code audio} with {@code otherAudio} and {@code interrupted}. + *

Audio focus for the soundtrack, which follows the game's own + * music switch alone: while it's on, the game takes focus each time it comes + * to the front, whatever else was playing, and holds it until it stops, not + * merely pauses; while it's off, the game holds none and the player's own + * music plays on ({@link AudioFocusPolicy}). A call or an alarm pauses + * everything until it ends. Call: {@code audioFocus} with {@code wanted}. + * Event: {@code audio} with {@code interrupted}. * *

Battery saver is iOS's Low Power Mode: the game holds its frame * rate to 60 while it is on. Event: {@code powerSave}. @@ -64,7 +64,10 @@ public final class DeviceServices implements AudioManager.OnAudioFocusChangeList private final AudioManager audio; private final PowerManager power; private AudioFocusRequest focusRequest; + /** Holds a focus request: granted, or delayed until a call ends. */ private boolean hasFocus; + /** What the game was last told: a call or an alarm has the audio. */ + private boolean interrupted; private final AudioFocusPolicy focusPolicy = new AudioFocusPolicy(); private final BroadcastReceiver powerSaveReceiver = new BroadcastReceiver() { @@ -107,6 +110,11 @@ public JSONObject call(String method, JSONObject args) { }); return null; } + case "audioFocus": { + boolean wanted = args.optBoolean("wanted", true); + activity.runOnUiThread(() -> apply(focusPolicy.onWanted(wanted, hasFocus))); + return null; + } case "state": return PlatformServices.object( "powerSave", power != null && power.isPowerSaveMode(), @@ -259,19 +267,9 @@ private void showStatusBar(boolean visible) { @Override public void onResume() { postPowerSave(); - if (audio == null) return; - // Before SDL resumes the game's own stream, which is stopped only - // after a stop (`AudioFocusPolicy`). - switch (focusPolicy.onResume(hasFocus, audio.isMusicActive())) { - case OTHER_AUDIO: - services.post(SERVICE, "audio", PlatformServices.object("otherAudio", true, "interrupted", false)); - break; - case REQUEST: - requestFocus(); - break; - case KEEP: - break; - } + apply(focusPolicy.onResume(hasFocus)); + // With no focus, nothing will say an interruption ended. + if (!hasFocus) setInterrupted(false); } @Override @@ -296,6 +294,20 @@ private void postPowerSave() { // MARK: - Audio focus + private void apply(AudioFocusPolicy.Step step) { + switch (step) { + case REQUEST: + requestFocus(); + break; + case ABANDON: + abandonFocus(); + setInterrupted(false); + break; + case KEEP: + break; + } + } + private void requestFocus() { if (audio == null || hasFocus) return; int result; @@ -306,6 +318,8 @@ private void requestFocus() { .setUsage(AudioAttributes.USAGE_GAME) .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC) .build()) + // Asked during a call: granted as it ends. + .setAcceptsDelayedFocusGain(true) .setOnAudioFocusChangeListener(this) .build(); } @@ -313,8 +327,15 @@ private void requestFocus() { } else { result = audio.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN); } - hasFocus = result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED; - services.post(SERVICE, "audio", PlatformServices.object("otherAudio", !hasFocus, "interrupted", false)); + boolean delayed = result == AudioManager.AUDIOFOCUS_REQUEST_DELAYED; + hasFocus = delayed || result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED; + setInterrupted(delayed); + } + + private void setInterrupted(boolean interrupted) { + if (interrupted == this.interrupted) return; + this.interrupted = interrupted; + services.post(SERVICE, "audio", PlatformServices.object("interrupted", interrupted)); } private void abandonFocus() { @@ -332,17 +353,18 @@ public void onAudioFocusChange(int change) { switch (change) { case AudioManager.AUDIOFOCUS_GAIN: hasFocus = true; - services.post(SERVICE, "audio", PlatformServices.object("otherAudio", false, "interrupted", false)); + setInterrupted(false); break; case AudioManager.AUDIOFOCUS_LOSS: - // Another app's music: the soundtrack steps aside for good, - // until the game next comes to the front. + // The player started another app's music over the game: + // Android fades the game out until it next comes back from a + // stop and asks again (`AudioFocusPolicy`). abandonFocus(); - services.post(SERVICE, "audio", PlatformServices.object("otherAudio", true, "interrupted", false)); + setInterrupted(false); break; case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT: // A call or an alarm: everything waits. - services.post(SERVICE, "audio", PlatformServices.object("otherAudio", false, "interrupted", true)); + setInterrupted(true); break; default: // LOSS_TRANSIENT_CAN_DUCK: the system ducks us itself. diff --git a/Library/spritekit/src/test/java/com/spritekit/platform/AudioFocusPolicyTest.java b/Library/spritekit/src/test/java/com/spritekit/platform/AudioFocusPolicyTest.java index d3a3c700..6ee29174 100644 --- a/Library/spritekit/src/test/java/com/spritekit/platform/AudioFocusPolicyTest.java +++ b/Library/spritekit/src/test/java/com/spritekit/platform/AudioFocusPolicyTest.java @@ -6,44 +6,76 @@ public class AudioFocusPolicyTest { @Test - public void firstStartAsksForFocusWhenNothingPlays() { + public void asksAsTheGameSaysItWantsFocus() { AudioFocusPolicy policy = new AudioFocusPolicy(); - assertEquals(AudioFocusPolicy.Step.REQUEST, policy.onResume(false, false)); + assertEquals(AudioFocusPolicy.Step.KEEP, policy.onResume(false)); + assertEquals(AudioFocusPolicy.Step.REQUEST, policy.onWanted(true, false)); } @Test - public void firstStartStepsAsideForOtherMusic() { + public void asksAtTheFirstStartWhenTheGameSaidSoBefore() { AudioFocusPolicy policy = new AudioFocusPolicy(); - assertEquals(AudioFocusPolicy.Step.OTHER_AUDIO, policy.onResume(false, true)); + assertEquals(AudioFocusPolicy.Step.KEEP, policy.onWanted(true, false)); + assertEquals(AudioFocusPolicy.Step.REQUEST, policy.onResume(false)); } /** - * The regression: a pause without a stop (a dialog, the shade's device - * controls, a second launch intent) leaves the game's own soundtrack - * playing, so `isMusicActive()` reads true. The game keeps its focus and - * mustn't take its own music for another app's. + * The regression: coming back from a stop while another app's music + * plays (or after it took focus and Android faded the game out), the + * game asks again, so its soundtrack comes back. */ @Test - public void pauseWithoutStopKeepsFocusThoughItsOwnMusicPlays() { + public void backFromAStopAsksAgain() { AudioFocusPolicy policy = new AudioFocusPolicy(); - policy.onResume(false, false); - assertEquals(AudioFocusPolicy.Step.KEEP, policy.onResume(true, true)); + policy.onWanted(true, false); + policy.onResume(false); + policy.onStop(); + assertEquals(AudioFocusPolicy.Step.REQUEST, policy.onResume(false)); } @Test - public void pauseWithoutStopAndNoFocusChangesNothing() { + public void pauseWithoutStopKeepsWhatItHas() { AudioFocusPolicy policy = new AudioFocusPolicy(); - policy.onResume(false, true); - assertEquals(AudioFocusPolicy.Step.KEEP, policy.onResume(false, true)); + policy.onWanted(true, false); + policy.onResume(false); + assertEquals(AudioFocusPolicy.Step.KEEP, policy.onResume(true)); + assertEquals(AudioFocusPolicy.Step.KEEP, policy.onResume(false)); } @Test - public void backFromAStopLooksForOtherMusicAgain() { + public void musicOffHoldsNoFocus() { AudioFocusPolicy policy = new AudioFocusPolicy(); - policy.onResume(false, false); + policy.onWanted(false, false); + assertEquals(AudioFocusPolicy.Step.KEEP, policy.onResume(false)); policy.onStop(); - assertEquals(AudioFocusPolicy.Step.OTHER_AUDIO, policy.onResume(false, true)); + assertEquals(AudioFocusPolicy.Step.KEEP, policy.onResume(false)); + } + + @Test + public void theSwitchTakesAndGivesUpFocusInTheFront() { + AudioFocusPolicy policy = new AudioFocusPolicy(); + policy.onWanted(false, false); + policy.onResume(false); + assertEquals(AudioFocusPolicy.Step.REQUEST, policy.onWanted(true, false)); + assertEquals(AudioFocusPolicy.Step.ABANDON, policy.onWanted(false, true)); + } + + /** The same switch told again (a sync) doesn't take focus back from the player's own music. */ + @Test + public void theSameSwitchAgainChangesNothing() { + AudioFocusPolicy policy = new AudioFocusPolicy(); + policy.onWanted(true, false); + policy.onResume(false); + assertEquals(AudioFocusPolicy.Step.KEEP, policy.onWanted(true, false)); + } + + @Test + public void theSwitchInTheBackgroundWaitsForTheFront() { + AudioFocusPolicy policy = new AudioFocusPolicy(); + policy.onWanted(false, false); + policy.onResume(false); policy.onStop(); - assertEquals(AudioFocusPolicy.Step.REQUEST, policy.onResume(false, false)); + assertEquals(AudioFocusPolicy.Step.KEEP, policy.onWanted(true, false)); + assertEquals(AudioFocusPolicy.Step.REQUEST, policy.onResume(false)); } } diff --git a/Platform/Sources/PlatformAndroid/AndroidPlatformServices.swift b/Platform/Sources/PlatformAndroid/AndroidPlatformServices.swift index 7d2a77bb..88cf271e 100644 --- a/Platform/Sources/PlatformAndroid/AndroidPlatformServices.swift +++ b/Platform/Sources/PlatformAndroid/AndroidPlatformServices.swift @@ -43,9 +43,9 @@ public enum AndroidPlatformServices { /// Purchases, made whether or not there's a channel. public var billing: Billing? - /// Told when audio focus changes (the `audio` event): whether other - /// audio is playing, and whether a call interrupted the game. - public var audioFocusChanged: ((_ otherAudio: Bool, _ interrupted: Bool) -> Void)? + /// Audio focus for the game's soundtrack. With none, the game takes + /// focus every time it comes to the front and nothing hears of calls. + public var audio: Audio? /// The settings' status bar switch, shown or hidden as it changes. public var statusBar: StatusBar? /// The battery and connection a game's diagnostics read @@ -83,6 +83,25 @@ public enum AndroidPlatformServices { } } + /// When the game wants audio focus, and who hears of calls. + public struct Audio { + /// Whether the game wants focus: while its music is on. The game asks + /// for it each time it comes to the front, so its soundtrack plays + /// whatever another app was playing; with music off, the player's + /// own music keeps playing under the game's sounds. + public var wantsFocus: () -> Bool + /// Posted when `wantsFocus` may have changed. + public var changed: Notification.Name + /// A call or an alarm took the audio, or gave it back (the `audio` event). + public var interrupted: (Bool) -> Void + + public init(wantsFocus: @escaping () -> Bool, changed: Notification.Name, interrupted: @escaping (Bool) -> Void) { + self.wantsFocus = wantsFocus + self.changed = changed + self.interrupted = interrupted + } + } + public struct StatusBar { public var isVisible: () -> Bool /// Posted when the switch changes. @@ -182,7 +201,7 @@ public enum AndroidPlatformServices { } } let center = configuration.notificationCenter - let audioFocusChanged = configuration.audioFocusChanged + let audio = configuration.audio channel.on("device") { event, body in switch event { case "powerSave": @@ -192,11 +211,15 @@ public enum AndroidPlatformServices { // As iOS posts Low Power Mode changing. center.post(name: .NSProcessInfoPowerStateDidChange, object: nil) case "audio": - audioFocusChanged?(body.bool("otherAudio") ?? false, body.bool("interrupted") ?? false) + audio?.interrupted(body.bool("interrupted") ?? false) default: break } } + // The shell waits to hear before it asks for focus. + let wantsFocus = { _ = channel.call("device.audioFocus", ["wanted": audio?.wantsFocus() ?? true]) } + if let audio { installed.observers.observe(audio.changed) { _ in wantsFocus() } } + wantsFocus() if let statusBar = configuration.statusBar { let show = { _ = channel.call("device.statusBar", ["visible": statusBar.isVisible()]) } installed.observers.observe(statusBar.changed) { _ in show() } diff --git a/Platform/Sources/PlatformAndroidHost/ToolkitServices.swift b/Platform/Sources/PlatformAndroidHost/ToolkitServices.swift index 00fe8184..5e3e0ec8 100644 --- a/Platform/Sources/PlatformAndroidHost/ToolkitServices.swift +++ b/Platform/Sources/PlatformAndroidHost/ToolkitServices.swift @@ -39,9 +39,7 @@ extension AndroidPlatformServices.Configuration { services.billing = .init(store: store) } if let audio { - services.audioFocusChanged = { otherAudio, interrupted in - MainActor.assumeIsolated { audio.audioFocusDidChange(otherAudio: otherAudio, interrupted: interrupted) } - } + services.audio = .manager(audio) } if statusBar { services.statusBar = .setting @@ -50,6 +48,17 @@ extension AndroidPlatformServices.Configuration { } } +extension AndroidPlatformServices.Audio { + /// `audio`'s: focus while its music is on, calls suspending it. + public static func manager(_ audio: AudioManager) -> Self { + .init( + wantsFocus: { MainActor.assumeIsolated { audio.musicEnabled } }, + changed: AudioManager.musicEnabledDidChange, + interrupted: { interrupted in MainActor.assumeIsolated { audio.audioFocusDidChange(interrupted: interrupted) } } + ) + } +} + extension AndroidPlatformServices.StatusBar { /// The settings' switch, `StatusBarSetting`. public static var setting: Self { diff --git a/Platform/Sources/PlatformAudio/AppleAudioBackend.swift b/Platform/Sources/PlatformAudio/AppleAudioBackend.swift index 22f4408b..59f07530 100644 --- a/Platform/Sources/PlatformAudio/AppleAudioBackend.swift +++ b/Platform/Sources/PlatformAudio/AppleAudioBackend.swift @@ -12,21 +12,18 @@ import UIKit /// plays its intro once, then repeats its loop section seamlessly, and /// tracks crossfade on player nodes of their own (`MusicDeck`). /// -/// It looks after the system's side itself: an ambient session (the -/// player's own music keeps playing), and picking the soundtrack up where it -/// was after an interruption, a route change or the app's time in the -/// background, which stop the engine. +/// It looks after the system's side itself: an ambient session, and picking +/// the soundtrack up where it was after an interruption, a route change or +/// the app's time in the background, which stop the engine. +/// +/// Ambient mixes with other apps' audio, so the player's own music keeps +/// playing under the game's, no other app's playback interrupts it, and the +/// Ring/Silent switch silences it as it does every game. Only calls, Siri and +/// alarms interrupt it; the soundtrack comes back as they end, or at the +/// latest as the app is next active. public final class AppleAudioBackend: AudioBackend { private static let fadeStep: TimeInterval = 1.0 / 60 - /// Told when another app starts or stops playing audio - /// (`secondaryAudioShouldBeSilencedHint`). - public var onOtherAudioChange: ((Bool) -> Void)? - - public var isOtherAudioPlaying: Bool { - AVAudioSession.sharedInstance().secondaryAudioShouldBeSilencedHint - } - private let bundle: Bundle private let soundExtensions: [String] private let musicExtensions: [String] @@ -68,10 +65,9 @@ public final class AppleAudioBackend: AudioBackend { self.soundExtensions = soundExtensions self.musicExtensions = musicExtensions sessionQueue.async { - let session = AVAudioSession.sharedInstance() - try? session.setCategory(.ambient, options: [.mixWithOthers]) - try? session.setActive(true) + try? AVAudioSession.sharedInstance().setCategory(.ambient) } + activateSession() observe() } @@ -84,23 +80,40 @@ public final class AppleAudioBackend: AudioBackend { } } } - on(AVAudioSession.silenceSecondaryAudioHintNotification) { backend, _ in - backend.onOtherAudioChange?(backend.isOtherAudioPlaying) - } on(AVAudioSession.interruptionNotification) { backend, notification in - let type = notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt - if type == AVAudioSession.InterruptionType.began.rawValue { - backend.musicStopped(pausing: true) - } else { - backend.restartMusic() + let info = notification.userInfo ?? [:] + guard (info[AVAudioSessionInterruptionTypeKey] as? UInt).flatMap(AVAudioSession.InterruptionType.init) == .began else { + backend.activateSession(thenRestart: true) + return } + // An interruption that came while the app was suspended is told + // as it comes back, long over: pausing for it would keep the + // soundtrack quiet with no end to come. + guard info[AVAudioSessionInterruptionReasonKey] as? UInt != AVAudioSession.InterruptionReason.appWasSuspended.rawValue, + info[AVAudioSessionInterruptionWasSuspendedKey] as? Bool != true else { return } + backend.musicStopped(pausing: true) } on(.AVAudioEngineConfigurationChange, engine) { backend, _ in backend.musicStopped(pausing: false) backend.restartMusic() } on(UIApplication.didEnterBackgroundNotification) { backend, _ in backend.suspend() } - on(UIApplication.willEnterForegroundNotification) { backend, _ in backend.resume() } + // Active rather than entering the foreground: the app may play only + // once it's active, and it's active again too after an interruption + // that never said it ended (Siri, a call declined). + on(UIApplication.didBecomeActiveNotification) { backend, _ in backend.resume() } + } + + /// Activates the session (again, after an interruption ended it) off the + /// main thread, then picks the soundtrack up if `thenRestart`. + private func activateSession(thenRestart: Bool = false) { + sessionQueue.async { [weak self] in + try? AVAudioSession.sharedInstance().setActive(true) + guard thenRestart else { return } + DispatchQueue.main.async { + MainActor.assumeIsolated { self?.restartMusic() } + } + } } private func url(of name: String, _ extensions: [String]) -> URL? { @@ -217,7 +230,7 @@ public final class AppleAudioBackend: AudioBackend { public func resume() { isInBackground = false - restartMusic() + activateSession(thenRestart: true) } /// Plays the current track again if the engine stopped under it. diff --git a/Platform/Sources/PlatformAudio/AudioConfiguration.swift b/Platform/Sources/PlatformAudio/AudioConfiguration.swift index 2d1fcfee..851d3fd2 100644 --- a/Platform/Sources/PlatformAudio/AudioConfiguration.swift +++ b/Platform/Sources/PlatformAudio/AudioConfiguration.swift @@ -71,9 +71,6 @@ public struct AudioConfiguration { /// The file of variant `index` (from 1) of a sound or track asked for /// with `variants:`. public var variantName: (String, Int) -> String - /// The soundtrack steps aside while another app plays audio (iOS's - /// secondary-audio hint, Android's audio focus); sounds still mix in. - public var stepsAsideForOtherAudio: Bool public var settings: Settings /// Told every sound asked for, by file name, whether or not sound is /// on: for a game that logs or records them. @@ -92,7 +89,6 @@ public struct AudioConfiguration { soundExtensions: [String] = ["wav", "caf", "m4a", "mp3"], musicExtensions: [String] = ["m4a", "mp3", "aac", "caf", "wav"], variantName: @escaping (String, Int) -> String = { "\($0) \($1)" }, - stepsAsideForOtherAudio: Bool = true, settings: Settings = Settings(), onSound: ((String) -> Void)? = nil ) { @@ -108,7 +104,6 @@ public struct AudioConfiguration { self.soundExtensions = soundExtensions self.musicExtensions = musicExtensions self.variantName = variantName - self.stepsAsideForOtherAudio = stepsAsideForOtherAudio self.settings = settings self.onSound = onSound } diff --git a/Platform/Sources/PlatformAudio/AudioManager.swift b/Platform/Sources/PlatformAudio/AudioManager.swift index ec7951ab..2fc1f33a 100644 --- a/Platform/Sources/PlatformAudio/AudioManager.swift +++ b/Platform/Sources/PlatformAudio/AudioManager.swift @@ -7,8 +7,10 @@ import PlatformCore /// /// Every decision about what should be heard is made here, the same on /// every platform: whether sound and music are switched on, which track the -/// screen asked for, whether a jingle has the music ducked or another app's -/// audio has it stepping aside. A backend only plays what it's told. +/// screen asked for, whether a jingle has the music ducked. The soundtrack +/// follows the game's own music switch alone: other apps' audio never +/// silences it (it mixes in on Apple platforms; on Android the game takes +/// audio focus while its music is on). A backend only plays what it's told. /// /// Sounds play from small pools of voices, so quick repeats overlap; one /// played with `playEffect` gets a voice of its own that can loop and be @@ -17,6 +19,9 @@ import PlatformCore public final class AudioManager { public static let shared = AudioManager() + /// Posted when the music switch changes, here or on another device. + public static let musicEnabledDidChange = Notification.Name("AudioManager.musicEnabledDidChange") + public private(set) var configuration = AudioConfiguration() public private(set) var backend: AudioBackend private let clock: AudioClock @@ -43,7 +48,6 @@ public final class AudioManager { private var isPaused = false private var isDucked = false private var ducks = 0 - private var otherAudio = false private var isInterrupted = false /// What the backend was last told: its track and volume. private var sentTrack: String? @@ -81,15 +85,6 @@ public final class AudioManager { /// into it and starts the track the game asked for meanwhile. public func use(_ backend: AudioBackend) { self.backend = backend - #if !SPRITEKIT_SHIM - if let apple = backend as? AppleAudioBackend { - otherAudio = apple.isOtherAudioPlaying - apple.onOtherAudioChange = { [weak self] playing in - guard let self else { return } - self.audioFocusDidChange(otherAudio: playing, interrupted: self.isInterrupted) - } - } - #endif let names = configuration.sounds.map(\.name) + prepared.subtracting(configuration.sounds.map(\.name)).sorted() prepared = [] prepare(names) @@ -98,18 +93,13 @@ public final class AudioManager { updateMusic(fade: 0) } - /// What the platform says about other audio: another app's music is - /// playing (`otherAudio`: the soundtrack steps aside, if the game - /// wants it to), or a call or alarm has taken the audio altogether - /// (`interrupted`: everything waits). Android's audio focus arrives - /// here; on Apple platforms the backend reports it itself. - public func audioFocusDidChange(otherAudio: Bool, interrupted: Bool) { - if interrupted != isInterrupted { - isInterrupted = interrupted - if interrupted { backend.suspend() } else { backend.resume() } - } - self.otherAudio = otherAudio - updateMusic(fade: configuration.musicFadeDuration) + /// A call or an alarm took the audio (`interrupted`: everything waits), + /// or gave it back. Android's audio focus arrives here; on Apple + /// platforms the backend looks after interruptions itself. + public func audioFocusDidChange(interrupted: Bool) { + guard interrupted != isInterrupted else { return } + isInterrupted = interrupted + if interrupted { backend.suspend() } else { backend.resume() } } // MARK: Settings @@ -142,6 +132,7 @@ public final class AudioManager { set { configuration.settings.write(newValue, configuration.settings.musicKey) updateMusic(fade: configuration.musicFadeDuration) + NotificationCenter.default.post(name: Self.musicEnabledDidChange, object: self) } } @@ -152,7 +143,10 @@ public final class AudioManager { public func savedDataDidSync(_ keys: Set) { if keys.contains(configuration.settings.soundKey), !soundEnabled { stopLoopingEffects() } - if keys.contains(configuration.settings.musicKey) { updateMusic(fade: configuration.musicFadeDuration) } + if keys.contains(configuration.settings.musicKey) { + updateMusic(fade: configuration.musicFadeDuration) + NotificationCenter.default.post(name: Self.musicEnabledDidChange, object: self) + } } // MARK: Files @@ -330,7 +324,7 @@ public final class AudioManager { /// Tells the backend what should be heard now, if that changed. private func updateMusic(fade: TimeInterval) { - let silent = !musicEnabled || isPaused || (otherAudio && configuration.stepsAsideForOtherAudio) + let silent = !musicEnabled || isPaused let wanted = silent ? nil : requested let volume = isDucked ? min(configuration.duckedMusicVolume, configuration.musicVolume) : configuration.musicVolume guard wanted?.file != sentTrack || (wanted != nil && volume != sentVolume) else { return } diff --git a/Platform/Tests/PlatformAndroidHostTests/PlatformAndroidHostTests.swift b/Platform/Tests/PlatformAndroidHostTests/PlatformAndroidHostTests.swift index 851cb21d..f53fdc5d 100644 --- a/Platform/Tests/PlatformAndroidHostTests/PlatformAndroidHostTests.swift +++ b/Platform/Tests/PlatformAndroidHostTests/PlatformAndroidHostTests.swift @@ -176,12 +176,12 @@ struct ToolkitServicesTests { #expect(services.leaderboards != nil) #expect(services.cloud != nil) #expect(services.billing == nil) - #expect(services.audioFocusChanged != nil) + #expect(services.audio != nil) let bare = AndroidPlatformServices.Configuration.toolkit(gameCenter: nil, syncsSavedData: false, audio: nil) #expect(bare.achievements == nil) #expect(bare.leaderboards == nil) #expect(bare.cloud == nil) - #expect(bare.audioFocusChanged == nil) + #expect(bare.audio == nil) } @Test("Play Billing takes the store's products, its consumables and the server's") diff --git a/Platform/Tests/PlatformAndroidTests/PlatformAndroidTests.swift b/Platform/Tests/PlatformAndroidTests/PlatformAndroidTests.swift index 2175918d..358bfd58 100644 --- a/Platform/Tests/PlatformAndroidTests/PlatformAndroidTests.swift +++ b/Platform/Tests/PlatformAndroidTests/PlatformAndroidTests.swift @@ -122,12 +122,14 @@ struct AndroidWiringTests { func device() { let java = FakeJava() let center = NotificationCenter() - var focus: (Bool, Bool)? + var interrupted: Bool? + var wantsFocus = true + let musicChanged = Notification.Name("test.music") var statusBarVisible = true let statusBarChanged = Notification.Name("test.statusBar") var config = configuration(java, center) config.playGames = nil - config.audioFocusChanged = { focus = ($0, $1) } + config.audio = .init(wantsFocus: { wantsFocus }, changed: musicChanged, interrupted: { interrupted = $0 }) config.diagnostics = true config.statusBar = .init(isVisible: { statusBarVisible }, changed: statusBarChanged) @@ -147,12 +149,17 @@ struct AndroidWiringTests { java.channel.deliver([ ["service": "device", "event": "powerSave", "enabled": false], ["service": "device", "event": "powerSave", "enabled": false], - ["service": "device", "event": "audio", "otherAudio": true, "interrupted": false], + ["service": "device", "event": "audio", "interrupted": true], ]) center.removeObserver(observer) #expect(!Device.lowPowerMode) #expect(powerChanges == 1) - #expect(focus.map { [$0.0, $0.1] } == [true, false]) + #expect(interrupted == true) + + #expect(java.calls.last(where: { $0.name == "device.audioFocus" })?.arguments["wanted"] as? Bool == true) + wantsFocus = false + center.post(name: musicChanged, object: nil) + #expect(java.calls.last(where: { $0.name == "device.audioFocus" })?.arguments["wanted"] as? Bool == false) #expect(java.calls.last(where: { $0.name == "device.statusBar" })?.arguments["visible"] as? Bool == true) statusBarVisible = false diff --git a/Platform/Tests/PlatformAudioTests/AudioManagerTests.swift b/Platform/Tests/PlatformAudioTests/AudioManagerTests.swift index bd02244f..441779bb 100644 --- a/Platform/Tests/PlatformAudioTests/AudioManagerTests.swift +++ b/Platform/Tests/PlatformAudioTests/AudioManagerTests.swift @@ -274,22 +274,28 @@ struct MusicTests { #expect(harness.music.last?.volume == 0.4) } - @Test func otherAudioHasTheSoundtrackStepAsideAndInterruptionsSuspend() { + @Test func interruptionsSuspendAndResumeWithoutTouchingTheTrack() { let harness = Harness() harness.audio.playMusic(Track.menu) - harness.audio.audioFocusDidChange(otherAudio: true, interrupted: false) - #expect(harness.backend.track == nil) - harness.audio.audioFocusDidChange(otherAudio: false, interrupted: true) + harness.audio.audioFocusDidChange(interrupted: true) + #expect(harness.backend.track == "Menu") + harness.audio.audioFocusDidChange(interrupted: true) + harness.audio.audioFocusDidChange(interrupted: false) #expect(harness.backend.track == "Menu") - harness.audio.audioFocusDidChange(otherAudio: false, interrupted: false) #expect(harness.backend.calls.filter { $0 == .suspend || $0 == .resume } == [.suspend, .resume]) } - @Test func gamesMayKeepTheirMusicThroughOtherAudio() { - let harness = Harness { $0.stepsAsideForOtherAudio = false } - harness.audio.playMusic(Track.menu) - harness.audio.audioFocusDidChange(otherAudio: true, interrupted: false) - #expect(harness.backend.track == "Menu") + @Test func theMusicSwitchIsPostedWhenItChanges() { + let harness = Harness() + var posts = 0 + let observer = NotificationCenter.default.addObserver(forName: AudioManager.musicEnabledDidChange, object: harness.audio, queue: nil) { _ in + posts += 1 + } + defer { NotificationCenter.default.removeObserver(observer) } + harness.audio.musicEnabled = false + harness.audio.savedDataDidSync([harness.audio.configuration.settings.soundKey]) + harness.audio.savedDataDidSync([harness.audio.configuration.settings.musicKey]) + #expect(posts == 2) } @Test func aNewBackendGetsTheSoundsAndTheTrack() { diff --git a/README.md b/README.md index d238983d..a13bdf11 100644 --- a/README.md +++ b/README.md @@ -91,7 +91,7 @@ IDs, achievement IDs, constants), and the module does the rest. | --- | --- | | `PlatformCore` | Geometry shorthands, timing curves and eased `SKAction`s, a node added at its z-position in one line, action keys as an enum, seeded randomness you can replay, a launch-argument reader for debug switches, notification observers removed together (`ObserverBag`), stepping through an enum's cases (`index`, `next()`, `previous()`) | | `PlatformSprite` | A texture cache and sprite helpers, path and label builders, colours, text and font handling, SVG paths drawn as icons, shape sprites without `SKShapeNode`, scenes built off the main thread behind a loading screen, a studio's launch splash, safe-area layout, localization, debug markers | -| `PlatformAudio` | Sound effects, and a soundtrack that loops seamlessly, crossfades between tracks, ducks for a jingle and steps aside for other apps' audio | +| `PlatformAudio` | Sound effects, and a soundtrack that loops seamlessly, crossfades between tracks, ducks for a jingle, and follows only the game's music switch, whatever other apps play | | `PlatformStore` | In-app purchases (StoreKit 2, or Play Billing): products, entitlements, restores, promoted purchases | | `PlatformGameCenter` | Sign-in, achievements and leaderboards that catch up from saved progress (GameKit, or Play Games) | | `PlatformSync` | Saved data synced across a player's devices (iCloud's key-value store, or Play's Saved Games), with sets that merge instead of overwrite | @@ -413,9 +413,13 @@ another crossfades in, nil fades out), `stopMusic`, `pauseMusic`, `AudioManager.isSoundEnabled` and `isMusicEnabled` are the settings' switches, saved under `settings.soundEnabled` and `settings.musicEnabled` unless the configuration says otherwise, and `savedDataDidSync(_:)` follows -another device's. Android's audio focus arrives through -`audioFocusDidChange(otherAudio:interrupted:)`; on Apple platforms the backend -reports another app's audio itself. Whatever a backend can't do (a voice of +another device's (posting `musicEnabledDidChange`). Other apps' audio never +silences the soundtrack: on Apple platforms the session is ambient, so the +player's own music mixes in and only calls, Siri and alarms interrupt (the +soundtrack comes back as they end, or as the app is next active); on Android +the game takes audio focus each time it comes to the front while its music +is on (`AndroidPlatformServices.Audio`, `.manager(_:)`), and calls reach +`audioFocusDidChange(interrupted:)`. Whatever a backend can't do (a voice of its own, on a backend without them) falls back to playing the sound once. ### Sprites, text and scenes (`PlatformSprite`) diff --git a/Templates/App/README.md b/Templates/App/README.md index 32a8eb81..80283bb0 100644 --- a/Templates/App/README.md +++ b/Templates/App/README.md @@ -35,7 +35,7 @@ them changes only its imports. | `spritekit` | `SpriteKitActivity` | SDL's activity: launch arguments in debuggable builds, the game's orientations (`OrientationPolicy`, + its test), the environment the runtime reads (below), Back on Android 13 and later, the safe area as iOS gives it, links (`gameLink`, held until the shell can take them, a cold start's as `-LaunchLink`), the share sheet (`shareFile`), Paste over a text field (`offerPaste`), the platform channel's JNI | | | `PlatformServices`, `PlatformService` | The channel's Java end: a registry of services by name, dispatching `service.method` calls and queueing events (`post`) | | | `DeviceServices` | `device`: haptics, battery saver, audio focus, the status bar, the app's settings page (`openAppSettings`), the battery (`battery`), the connection (`connection`, with the app's `ACCESS_NETWORK_STATE`), JPEG and PNG re-encoding (`jpegToPng`, `pngToJpeg`) | -| | `AudioFocusPolicy` (+ its test) | When to ask for audio focus, as an ambient iOS session behaves | +| | `AudioFocusPolicy` (+ its test) | When to ask for audio focus and give it up: each time the game comes to the front while its music is on | | | `PlayGamesServices` (+ `ScorePagingTest`) | `games`: sign-in, achievements, leaderboards (submitting, loading them and their scores, showing them at a time span and collection), the player, Saved Games | | | `PlayReview` | `review`: Play In-App Review, behind `SKStoreReviewController` | | `spritekit-billing` | `PlayBilling` | `billing`: one-time products (prices, purchases, acknowledgement, restore) and consumables (`consume`, each purchase's `quantity`) | From 0bb39dd5ee92ec6dcf3e77d0076829bdf8ab56a8 Mon Sep 17 00:00:00 2001 From: Himanshu Kapoor Date: Sat, 28 Nov 2026 12:20:49 +0100 Subject: [PATCH 2/3] PlatformAudio: configure tells Android's audio focus the music switch under the game's own key Services install before the game configures its audio, so the switch the shell first heard was read under the default key: configure posts musicEnabledDidChange too (the policy ignores a repeat). --- Platform/Sources/PlatformAudio/AudioManager.swift | 6 +++++- Platform/Tests/PlatformAudioTests/AudioManagerTests.swift | 3 +++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/Platform/Sources/PlatformAudio/AudioManager.swift b/Platform/Sources/PlatformAudio/AudioManager.swift index 2fc1f33a..959a2be0 100644 --- a/Platform/Sources/PlatformAudio/AudioManager.swift +++ b/Platform/Sources/PlatformAudio/AudioManager.swift @@ -19,7 +19,8 @@ import PlatformCore public final class AudioManager { public static let shared = AudioManager() - /// Posted when the music switch changes, here or on another device. + /// Posted when the music switch may have changed: set here, synced from + /// another device, or read under a new configuration. public static let musicEnabledDidChange = Notification.Name("AudioManager.musicEnabledDidChange") public private(set) var configuration = AudioConfiguration() @@ -70,6 +71,9 @@ public final class AudioManager { public func configure(_ configuration: AudioConfiguration) { self.configuration = configuration + // The switch may read otherwise under the game's own key or store, + // and whoever asked before (Android's audio focus) hears it again. + defer { NotificationCenter.default.post(name: Self.musicEnabledDidChange, object: self) } #if !SPRITEKIT_SHIM if backend is NullAudioBackend { use(AppleAudioBackend(soundExtensions: configuration.soundExtensions, musicExtensions: configuration.musicExtensions)) diff --git a/Platform/Tests/PlatformAudioTests/AudioManagerTests.swift b/Platform/Tests/PlatformAudioTests/AudioManagerTests.swift index 441779bb..531f828b 100644 --- a/Platform/Tests/PlatformAudioTests/AudioManagerTests.swift +++ b/Platform/Tests/PlatformAudioTests/AudioManagerTests.swift @@ -296,6 +296,9 @@ struct MusicTests { harness.audio.savedDataDidSync([harness.audio.configuration.settings.soundKey]) harness.audio.savedDataDidSync([harness.audio.configuration.settings.musicKey]) #expect(posts == 2) + // A new configuration may read the switch under another key. + harness.audio.configure(harness.audio.configuration) + #expect(posts == 3) } @Test func aNewBackendGetsTheSoundsAndTheTrack() { From e4f5771837a360baba8c374661a20e4dbdee6b29 Mon Sep 17 00:00:00 2001 From: Himanshu Kapoor Date: Sat, 28 Nov 2026 12:25:24 +0100 Subject: [PATCH 3/3] Android: no audio focus, as iOS's ambient session; nothing but the music switch silences the soundtrack The game holds no audio focus, so its soundtrack mixes with the player's own music, which plays on, and nothing (another app's playback, Android 12's fade-out, a call) silences it. Calls don't pause it either: only the game's music switch does. Gone with focus: AudioFocusPolicy, the device.audioFocus call and the audio event, AndroidPlatformServices.Configuration.audioFocusChanged, .toolkit's audio parameter, AudioManager.audioFocusDidChange and musicEnabledDidChange. --- AGENTS.md | 5 +- .../spritekit/platform/AudioFocusPolicy.java | 51 -------- .../spritekit/platform/DeviceServices.java | 120 +----------------- .../platform/AudioFocusPolicyTest.java | 81 ------------ .../AndroidPlatformServices.swift | 29 ----- .../PlatformAndroidHost/ToolkitServices.swift | 20 +-- .../PlatformAudio/AppleAudioBackend.swift | 6 +- .../Sources/PlatformAudio/AudioManager.swift | 29 +---- .../PlatformAndroidHostTests.swift | 4 +- .../PlatformAndroidTests.swift | 13 +- .../AudioManagerTests.swift | 25 +--- README.md | 19 ++- Templates/App/README.md | 3 +- 13 files changed, 34 insertions(+), 371 deletions(-) delete mode 100644 Library/spritekit/src/main/java/com/spritekit/platform/AudioFocusPolicy.java delete mode 100644 Library/spritekit/src/test/java/com/spritekit/platform/AudioFocusPolicyTest.java diff --git a/AGENTS.md b/AGENTS.md index 5aafbf41..68ac0b5d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -180,8 +180,9 @@ would want. a copy of the capture scripts. - Scenes play sounds and music with `PlatformAudio`'s `playSound`, `playMusic` and `stopMusic`, never a game's own wrappers of them. -- The soundtrack follows only the game's own music switch: no game silences - it for other apps' audio, which mixes in on Apple platforms. +- The soundtrack follows only the game's own music switch: it mixes with + other apps' audio on every platform (ambient on Apple, no audio focus on + Android), and no game pauses it for other audio or calls. - A game's soundtrack plays its intro once and then repeats a loop on the beat: its masters stay out of the bundle, and the runtime's `Tools/Audio/music.js` (its README), through the game's own two-line diff --git a/Library/spritekit/src/main/java/com/spritekit/platform/AudioFocusPolicy.java b/Library/spritekit/src/main/java/com/spritekit/platform/AudioFocusPolicy.java deleted file mode 100644 index 7e77c104..00000000 --- a/Library/spritekit/src/main/java/com/spritekit/platform/AudioFocusPolicy.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.spritekit.platform; - -/** - * When the game asks for audio focus and gives it up, apart from Android so - * a unit test can drive it ({@code AudioFocusPolicyTest}). - * - *

The game's soundtrack follows its own music switch alone. While the - * switch is on, the game asks for focus each time it comes back from a stop - * (and as it first starts), whatever another app is playing: Android fades - * out an app that lost focus and keeps it muted until it asks again, so a - * game that didn't ask would come back silent. Through a pause without a - * stop (a dialog or the shade's device controls over the game, a second - * launch intent, Play's sign-in) it keeps what it has: if the player - * started their own music meanwhile, it plays until the game next comes - * back. While the switch is off, the game holds no focus, so the player's - * own music plays on under the game's sounds. - */ -final class AudioFocusPolicy { - /** What to do about focus. */ - enum Step { - KEEP, - REQUEST, - ABANDON, - } - - /** Whether the game is stopped: before the first start, and after a stop. */ - private boolean stopped = true; - /** The game's music switch: null until the game says. */ - private Boolean wanted; - - Step onResume(boolean holdsFocus) { - boolean afterStop = stopped; - stopped = false; - return afterStop && !holdsFocus && Boolean.TRUE.equals(wanted) ? Step.REQUEST : Step.KEEP; - } - - /** The game went to the background: it gives focus up. */ - void onStop() { - stopped = true; - } - - /** The game says whether it wants focus (its music switch). */ - Step onWanted(boolean wanted, boolean holdsFocus) { - boolean changed = this.wanted == null || this.wanted != wanted; - this.wanted = wanted; - if (!changed || stopped) return Step.KEEP; - if (wanted && !holdsFocus) return Step.REQUEST; - if (!wanted && holdsFocus) return Step.ABANDON; - return Step.KEEP; - } -} diff --git a/Library/spritekit/src/main/java/com/spritekit/platform/DeviceServices.java b/Library/spritekit/src/main/java/com/spritekit/platform/DeviceServices.java index b6a0fea9..032daacc 100644 --- a/Library/spritekit/src/main/java/com/spritekit/platform/DeviceServices.java +++ b/Library/spritekit/src/main/java/com/spritekit/platform/DeviceServices.java @@ -8,8 +8,6 @@ import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.AudioAttributes; -import android.media.AudioFocusRequest; -import android.media.AudioManager; import android.net.ConnectivityManager; import android.net.Network; import android.net.NetworkCapabilities; @@ -32,7 +30,7 @@ import java.io.ByteArrayOutputStream; /** - * The device's part: haptics, audio focus, battery saver, the status bar, + * The device's part: haptics, battery saver, the status bar, * the app's settings page, the battery and the connection, and re-encoding * images between JPEG and PNG. * @@ -42,18 +40,15 @@ * and a short buzz on the oldest. Played as touch feedback, so the system's * own "vibration & haptics" switch silences them as it does every app's. * - *

Audio focus for the soundtrack, which follows the game's own - * music switch alone: while it's on, the game takes focus each time it comes - * to the front, whatever else was playing, and holds it until it stops, not - * merely pauses; while it's off, the game holds none and the player's own - * music plays on ({@link AudioFocusPolicy}). A call or an alarm pauses - * everything until it ends. Call: {@code audioFocus} with {@code wanted}. - * Event: {@code audio} with {@code interrupted}. + *

No audio focus, as the iOS build's ambient session: the game's + * soundtrack follows its own music switch alone and mixes with whatever else + * plays, the player's own music included, which plays on. Holding no focus, + * nothing (another app's playback, Android 12's fade-out) silences it. * *

Battery saver is iOS's Low Power Mode: the game holds its frame * rate to 60 while it is on. Event: {@code powerSave}. */ -public final class DeviceServices implements AudioManager.OnAudioFocusChangeListener, PlatformService { +public final class DeviceServices implements PlatformService { public static final String SERVICE = "device"; private final Activity activity; @@ -61,14 +56,7 @@ public final class DeviceServices implements AudioManager.OnAudioFocusChangeList /** The status bar the game last asked for: null until it asks. UI thread. */ private Boolean statusBarVisible; private final Vibrator vibrator; - private final AudioManager audio; private final PowerManager power; - private AudioFocusRequest focusRequest; - /** Holds a focus request: granted, or delayed until a call ends. */ - private boolean hasFocus; - /** What the game was last told: a call or an alarm has the audio. */ - private boolean interrupted; - private final AudioFocusPolicy focusPolicy = new AudioFocusPolicy(); private final BroadcastReceiver powerSaveReceiver = new BroadcastReceiver() { @Override @@ -86,7 +74,6 @@ public DeviceServices(Activity activity, PlatformServices services) { } else { vibrator = (Vibrator) activity.getSystemService(Context.VIBRATOR_SERVICE); } - audio = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE); power = (PowerManager) activity.getSystemService(Context.POWER_SERVICE); IntentFilter filter = new IntentFilter(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED); if (Build.VERSION.SDK_INT >= 33) { @@ -110,11 +97,6 @@ public JSONObject call(String method, JSONObject args) { }); return null; } - case "audioFocus": { - boolean wanted = args.optBoolean("wanted", true); - activity.runOnUiThread(() -> apply(focusPolicy.onWanted(wanted, hasFocus))); - return null; - } case "state": return PlatformServices.object( "powerSave", power != null && power.isPowerSaveMode(), @@ -267,20 +249,10 @@ private void showStatusBar(boolean visible) { @Override public void onResume() { postPowerSave(); - apply(focusPolicy.onResume(hasFocus)); - // With no focus, nothing will say an interruption ended. - if (!hasFocus) setInterrupted(false); - } - - @Override - public void onStop() { - focusPolicy.onStop(); - abandonFocus(); } @Override public void onDestroy() { - abandonFocus(); try { activity.unregisterReceiver(powerSaveReceiver); } catch (IllegalArgumentException alreadyGone) { @@ -292,86 +264,6 @@ private void postPowerSave() { services.post(SERVICE, "powerSave", PlatformServices.object("enabled", power != null && power.isPowerSaveMode())); } - // MARK: - Audio focus - - private void apply(AudioFocusPolicy.Step step) { - switch (step) { - case REQUEST: - requestFocus(); - break; - case ABANDON: - abandonFocus(); - setInterrupted(false); - break; - case KEEP: - break; - } - } - - private void requestFocus() { - if (audio == null || hasFocus) return; - int result; - if (Build.VERSION.SDK_INT >= 26) { - if (focusRequest == null) { - focusRequest = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN) - .setAudioAttributes(new AudioAttributes.Builder() - .setUsage(AudioAttributes.USAGE_GAME) - .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC) - .build()) - // Asked during a call: granted as it ends. - .setAcceptsDelayedFocusGain(true) - .setOnAudioFocusChangeListener(this) - .build(); - } - result = audio.requestAudioFocus(focusRequest); - } else { - result = audio.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN); - } - boolean delayed = result == AudioManager.AUDIOFOCUS_REQUEST_DELAYED; - hasFocus = delayed || result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED; - setInterrupted(delayed); - } - - private void setInterrupted(boolean interrupted) { - if (interrupted == this.interrupted) return; - this.interrupted = interrupted; - services.post(SERVICE, "audio", PlatformServices.object("interrupted", interrupted)); - } - - private void abandonFocus() { - if (audio == null || !hasFocus) return; - if (Build.VERSION.SDK_INT >= 26 && focusRequest != null) { - audio.abandonAudioFocusRequest(focusRequest); - } else { - audio.abandonAudioFocus(this); - } - hasFocus = false; - } - - @Override - public void onAudioFocusChange(int change) { - switch (change) { - case AudioManager.AUDIOFOCUS_GAIN: - hasFocus = true; - setInterrupted(false); - break; - case AudioManager.AUDIOFOCUS_LOSS: - // The player started another app's music over the game: - // Android fades the game out until it next comes back from a - // stop and asks again (`AudioFocusPolicy`). - abandonFocus(); - setInterrupted(false); - break; - case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT: - // A call or an alarm: everything waits. - setInterrupted(true); - break; - default: - // LOSS_TRANSIENT_CAN_DUCK: the system ducks us itself. - break; - } - } - // MARK: - Haptics private void haptic(String kind) { diff --git a/Library/spritekit/src/test/java/com/spritekit/platform/AudioFocusPolicyTest.java b/Library/spritekit/src/test/java/com/spritekit/platform/AudioFocusPolicyTest.java deleted file mode 100644 index 6ee29174..00000000 --- a/Library/spritekit/src/test/java/com/spritekit/platform/AudioFocusPolicyTest.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.spritekit.platform; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class AudioFocusPolicyTest { - @Test - public void asksAsTheGameSaysItWantsFocus() { - AudioFocusPolicy policy = new AudioFocusPolicy(); - assertEquals(AudioFocusPolicy.Step.KEEP, policy.onResume(false)); - assertEquals(AudioFocusPolicy.Step.REQUEST, policy.onWanted(true, false)); - } - - @Test - public void asksAtTheFirstStartWhenTheGameSaidSoBefore() { - AudioFocusPolicy policy = new AudioFocusPolicy(); - assertEquals(AudioFocusPolicy.Step.KEEP, policy.onWanted(true, false)); - assertEquals(AudioFocusPolicy.Step.REQUEST, policy.onResume(false)); - } - - /** - * The regression: coming back from a stop while another app's music - * plays (or after it took focus and Android faded the game out), the - * game asks again, so its soundtrack comes back. - */ - @Test - public void backFromAStopAsksAgain() { - AudioFocusPolicy policy = new AudioFocusPolicy(); - policy.onWanted(true, false); - policy.onResume(false); - policy.onStop(); - assertEquals(AudioFocusPolicy.Step.REQUEST, policy.onResume(false)); - } - - @Test - public void pauseWithoutStopKeepsWhatItHas() { - AudioFocusPolicy policy = new AudioFocusPolicy(); - policy.onWanted(true, false); - policy.onResume(false); - assertEquals(AudioFocusPolicy.Step.KEEP, policy.onResume(true)); - assertEquals(AudioFocusPolicy.Step.KEEP, policy.onResume(false)); - } - - @Test - public void musicOffHoldsNoFocus() { - AudioFocusPolicy policy = new AudioFocusPolicy(); - policy.onWanted(false, false); - assertEquals(AudioFocusPolicy.Step.KEEP, policy.onResume(false)); - policy.onStop(); - assertEquals(AudioFocusPolicy.Step.KEEP, policy.onResume(false)); - } - - @Test - public void theSwitchTakesAndGivesUpFocusInTheFront() { - AudioFocusPolicy policy = new AudioFocusPolicy(); - policy.onWanted(false, false); - policy.onResume(false); - assertEquals(AudioFocusPolicy.Step.REQUEST, policy.onWanted(true, false)); - assertEquals(AudioFocusPolicy.Step.ABANDON, policy.onWanted(false, true)); - } - - /** The same switch told again (a sync) doesn't take focus back from the player's own music. */ - @Test - public void theSameSwitchAgainChangesNothing() { - AudioFocusPolicy policy = new AudioFocusPolicy(); - policy.onWanted(true, false); - policy.onResume(false); - assertEquals(AudioFocusPolicy.Step.KEEP, policy.onWanted(true, false)); - } - - @Test - public void theSwitchInTheBackgroundWaitsForTheFront() { - AudioFocusPolicy policy = new AudioFocusPolicy(); - policy.onWanted(false, false); - policy.onResume(false); - policy.onStop(); - assertEquals(AudioFocusPolicy.Step.KEEP, policy.onWanted(true, false)); - assertEquals(AudioFocusPolicy.Step.REQUEST, policy.onResume(false)); - } -} diff --git a/Platform/Sources/PlatformAndroid/AndroidPlatformServices.swift b/Platform/Sources/PlatformAndroid/AndroidPlatformServices.swift index 88cf271e..1a7499f0 100644 --- a/Platform/Sources/PlatformAndroid/AndroidPlatformServices.swift +++ b/Platform/Sources/PlatformAndroid/AndroidPlatformServices.swift @@ -43,9 +43,6 @@ public enum AndroidPlatformServices { /// Purchases, made whether or not there's a channel. public var billing: Billing? - /// Audio focus for the game's soundtrack. With none, the game takes - /// focus every time it comes to the front and nothing hears of calls. - public var audio: Audio? /// The settings' status bar switch, shown or hidden as it changes. public var statusBar: StatusBar? /// The battery and connection a game's diagnostics read @@ -83,25 +80,6 @@ public enum AndroidPlatformServices { } } - /// When the game wants audio focus, and who hears of calls. - public struct Audio { - /// Whether the game wants focus: while its music is on. The game asks - /// for it each time it comes to the front, so its soundtrack plays - /// whatever another app was playing; with music off, the player's - /// own music keeps playing under the game's sounds. - public var wantsFocus: () -> Bool - /// Posted when `wantsFocus` may have changed. - public var changed: Notification.Name - /// A call or an alarm took the audio, or gave it back (the `audio` event). - public var interrupted: (Bool) -> Void - - public init(wantsFocus: @escaping () -> Bool, changed: Notification.Name, interrupted: @escaping (Bool) -> Void) { - self.wantsFocus = wantsFocus - self.changed = changed - self.interrupted = interrupted - } - } - public struct StatusBar { public var isVisible: () -> Bool /// Posted when the switch changes. @@ -201,7 +179,6 @@ public enum AndroidPlatformServices { } } let center = configuration.notificationCenter - let audio = configuration.audio channel.on("device") { event, body in switch event { case "powerSave": @@ -210,16 +187,10 @@ public enum AndroidPlatformServices { Device.lowPowerMode = enabled // As iOS posts Low Power Mode changing. center.post(name: .NSProcessInfoPowerStateDidChange, object: nil) - case "audio": - audio?.interrupted(body.bool("interrupted") ?? false) default: break } } - // The shell waits to hear before it asks for focus. - let wantsFocus = { _ = channel.call("device.audioFocus", ["wanted": audio?.wantsFocus() ?? true]) } - if let audio { installed.observers.observe(audio.changed) { _ in wantsFocus() } } - wantsFocus() if let statusBar = configuration.statusBar { let show = { _ = channel.call("device.statusBar", ["visible": statusBar.isVisible()]) } installed.observers.observe(statusBar.changed) { _ in show() } diff --git a/Platform/Sources/PlatformAndroidHost/ToolkitServices.swift b/Platform/Sources/PlatformAndroidHost/ToolkitServices.swift index 5e3e0ec8..06110deb 100644 --- a/Platform/Sources/PlatformAndroidHost/ToolkitServices.swift +++ b/Platform/Sources/PlatformAndroidHost/ToolkitServices.swift @@ -1,7 +1,6 @@ #if SPRITEKIT_SHIM import Foundation import PlatformAndroid -import PlatformAudio import PlatformDisplay import PlatformGameCenter import PlatformShim @@ -14,8 +13,8 @@ extension AndroidPlatformServices.Configuration { /// The toolkit's managers on Google Play and the device, as most games /// hand them: Play Games' achievements and leaderboards to /// `gameCenter`, Saved Games under `ICloudSyncManager` (`syncsSavedData`), - /// Play Billing to `store` for its configured products, and audio focus - /// to `audio`, and with `statusBar` the settings' switch + /// Play Billing to `store` for its configured products, and with + /// `statusBar` the settings' switch /// (`StatusBarSetting`) to the status bar. A manager left nil gets /// nothing. Set anything else (the player for GameKit's /// `GKLocalPlayer`, diagnostics) on the result before @@ -24,7 +23,6 @@ extension AndroidPlatformServices.Configuration { gameCenter: GameCenterManager?, syncsSavedData: Bool = true, store: StoreManager? = nil, - audio: AudioManager? = .shared, statusBar: Bool = false ) -> Self { var services = Self() @@ -38,9 +36,6 @@ extension AndroidPlatformServices.Configuration { if let store { services.billing = .init(store: store) } - if let audio { - services.audio = .manager(audio) - } if statusBar { services.statusBar = .setting } @@ -48,17 +43,6 @@ extension AndroidPlatformServices.Configuration { } } -extension AndroidPlatformServices.Audio { - /// `audio`'s: focus while its music is on, calls suspending it. - public static func manager(_ audio: AudioManager) -> Self { - .init( - wantsFocus: { MainActor.assumeIsolated { audio.musicEnabled } }, - changed: AudioManager.musicEnabledDidChange, - interrupted: { interrupted in MainActor.assumeIsolated { audio.audioFocusDidChange(interrupted: interrupted) } } - ) - } -} - extension AndroidPlatformServices.StatusBar { /// The settings' switch, `StatusBarSetting`. public static var setting: Self { diff --git a/Platform/Sources/PlatformAudio/AppleAudioBackend.swift b/Platform/Sources/PlatformAudio/AppleAudioBackend.swift index 59f07530..0015fef1 100644 --- a/Platform/Sources/PlatformAudio/AppleAudioBackend.swift +++ b/Platform/Sources/PlatformAudio/AppleAudioBackend.swift @@ -18,9 +18,9 @@ import UIKit /// /// Ambient mixes with other apps' audio, so the player's own music keeps /// playing under the game's, no other app's playback interrupts it, and the -/// Ring/Silent switch silences it as it does every game. Only calls, Siri and -/// alarms interrupt it; the soundtrack comes back as they end, or at the -/// latest as the app is next active. +/// Ring/Silent switch silences it as it does every game. The system still +/// silences it for a call, Siri or an alarm; the soundtrack comes back as +/// they end, or at the latest as the app is next active. public final class AppleAudioBackend: AudioBackend { private static let fadeStep: TimeInterval = 1.0 / 60 diff --git a/Platform/Sources/PlatformAudio/AudioManager.swift b/Platform/Sources/PlatformAudio/AudioManager.swift index 959a2be0..4c503fab 100644 --- a/Platform/Sources/PlatformAudio/AudioManager.swift +++ b/Platform/Sources/PlatformAudio/AudioManager.swift @@ -8,9 +8,9 @@ import PlatformCore /// Every decision about what should be heard is made here, the same on /// every platform: whether sound and music are switched on, which track the /// screen asked for, whether a jingle has the music ducked. The soundtrack -/// follows the game's own music switch alone: other apps' audio never -/// silences it (it mixes in on Apple platforms; on Android the game takes -/// audio focus while its music is on). A backend only plays what it's told. +/// follows the game's own music switch alone: it mixes with other apps' +/// audio (an ambient session on Apple platforms, no audio focus on Android), +/// and nothing else silences it. A backend only plays what it's told. /// /// Sounds play from small pools of voices, so quick repeats overlap; one /// played with `playEffect` gets a voice of its own that can loop and be @@ -19,10 +19,6 @@ import PlatformCore public final class AudioManager { public static let shared = AudioManager() - /// Posted when the music switch may have changed: set here, synced from - /// another device, or read under a new configuration. - public static let musicEnabledDidChange = Notification.Name("AudioManager.musicEnabledDidChange") - public private(set) var configuration = AudioConfiguration() public private(set) var backend: AudioBackend private let clock: AudioClock @@ -49,7 +45,6 @@ public final class AudioManager { private var isPaused = false private var isDucked = false private var ducks = 0 - private var isInterrupted = false /// What the backend was last told: its track and volume. private var sentTrack: String? private var sentVolume: Float = 0 @@ -71,9 +66,6 @@ public final class AudioManager { public func configure(_ configuration: AudioConfiguration) { self.configuration = configuration - // The switch may read otherwise under the game's own key or store, - // and whoever asked before (Android's audio focus) hears it again. - defer { NotificationCenter.default.post(name: Self.musicEnabledDidChange, object: self) } #if !SPRITEKIT_SHIM if backend is NullAudioBackend { use(AppleAudioBackend(soundExtensions: configuration.soundExtensions, musicExtensions: configuration.musicExtensions)) @@ -97,15 +89,6 @@ public final class AudioManager { updateMusic(fade: 0) } - /// A call or an alarm took the audio (`interrupted`: everything waits), - /// or gave it back. Android's audio focus arrives here; on Apple - /// platforms the backend looks after interruptions itself. - public func audioFocusDidChange(interrupted: Bool) { - guard interrupted != isInterrupted else { return } - isInterrupted = interrupted - if interrupted { backend.suspend() } else { backend.resume() } - } - // MARK: Settings /// The settings' keys, for a game that syncs them. @@ -136,7 +119,6 @@ public final class AudioManager { set { configuration.settings.write(newValue, configuration.settings.musicKey) updateMusic(fade: configuration.musicFadeDuration) - NotificationCenter.default.post(name: Self.musicEnabledDidChange, object: self) } } @@ -147,10 +129,7 @@ public final class AudioManager { public func savedDataDidSync(_ keys: Set) { if keys.contains(configuration.settings.soundKey), !soundEnabled { stopLoopingEffects() } - if keys.contains(configuration.settings.musicKey) { - updateMusic(fade: configuration.musicFadeDuration) - NotificationCenter.default.post(name: Self.musicEnabledDidChange, object: self) - } + if keys.contains(configuration.settings.musicKey) { updateMusic(fade: configuration.musicFadeDuration) } } // MARK: Files diff --git a/Platform/Tests/PlatformAndroidHostTests/PlatformAndroidHostTests.swift b/Platform/Tests/PlatformAndroidHostTests/PlatformAndroidHostTests.swift index f53fdc5d..04333c46 100644 --- a/Platform/Tests/PlatformAndroidHostTests/PlatformAndroidHostTests.swift +++ b/Platform/Tests/PlatformAndroidHostTests/PlatformAndroidHostTests.swift @@ -176,12 +176,10 @@ struct ToolkitServicesTests { #expect(services.leaderboards != nil) #expect(services.cloud != nil) #expect(services.billing == nil) - #expect(services.audio != nil) - let bare = AndroidPlatformServices.Configuration.toolkit(gameCenter: nil, syncsSavedData: false, audio: nil) + let bare = AndroidPlatformServices.Configuration.toolkit(gameCenter: nil, syncsSavedData: false) #expect(bare.achievements == nil) #expect(bare.leaderboards == nil) #expect(bare.cloud == nil) - #expect(bare.audio == nil) } @Test("Play Billing takes the store's products, its consumables and the server's") diff --git a/Platform/Tests/PlatformAndroidTests/PlatformAndroidTests.swift b/Platform/Tests/PlatformAndroidTests/PlatformAndroidTests.swift index 358bfd58..54c6c4d2 100644 --- a/Platform/Tests/PlatformAndroidTests/PlatformAndroidTests.swift +++ b/Platform/Tests/PlatformAndroidTests/PlatformAndroidTests.swift @@ -118,18 +118,14 @@ struct AndroidWiringTests { #expect(player?.name == "Player") } - @Test("Haptics, battery saver, audio focus, diagnostics and the status bar reach the device") + @Test("Haptics, battery saver, diagnostics and the status bar reach the device") func device() { let java = FakeJava() let center = NotificationCenter() - var interrupted: Bool? - var wantsFocus = true - let musicChanged = Notification.Name("test.music") var statusBarVisible = true let statusBarChanged = Notification.Name("test.statusBar") var config = configuration(java, center) config.playGames = nil - config.audio = .init(wantsFocus: { wantsFocus }, changed: musicChanged, interrupted: { interrupted = $0 }) config.diagnostics = true config.statusBar = .init(isVisible: { statusBarVisible }, changed: statusBarChanged) @@ -149,17 +145,10 @@ struct AndroidWiringTests { java.channel.deliver([ ["service": "device", "event": "powerSave", "enabled": false], ["service": "device", "event": "powerSave", "enabled": false], - ["service": "device", "event": "audio", "interrupted": true], ]) center.removeObserver(observer) #expect(!Device.lowPowerMode) #expect(powerChanges == 1) - #expect(interrupted == true) - - #expect(java.calls.last(where: { $0.name == "device.audioFocus" })?.arguments["wanted"] as? Bool == true) - wantsFocus = false - center.post(name: musicChanged, object: nil) - #expect(java.calls.last(where: { $0.name == "device.audioFocus" })?.arguments["wanted"] as? Bool == false) #expect(java.calls.last(where: { $0.name == "device.statusBar" })?.arguments["visible"] as? Bool == true) statusBarVisible = false diff --git a/Platform/Tests/PlatformAudioTests/AudioManagerTests.swift b/Platform/Tests/PlatformAudioTests/AudioManagerTests.swift index 531f828b..ef61ba17 100644 --- a/Platform/Tests/PlatformAudioTests/AudioManagerTests.swift +++ b/Platform/Tests/PlatformAudioTests/AudioManagerTests.swift @@ -274,31 +274,14 @@ struct MusicTests { #expect(harness.music.last?.volume == 0.4) } - @Test func interruptionsSuspendAndResumeWithoutTouchingTheTrack() { + @Test func onlyTheMusicSwitchSilencesTheSoundtrack() { let harness = Harness() harness.audio.playMusic(Track.menu) - harness.audio.audioFocusDidChange(interrupted: true) #expect(harness.backend.track == "Menu") - harness.audio.audioFocusDidChange(interrupted: true) - harness.audio.audioFocusDidChange(interrupted: false) - #expect(harness.backend.track == "Menu") - #expect(harness.backend.calls.filter { $0 == .suspend || $0 == .resume } == [.suspend, .resume]) - } - - @Test func theMusicSwitchIsPostedWhenItChanges() { - let harness = Harness() - var posts = 0 - let observer = NotificationCenter.default.addObserver(forName: AudioManager.musicEnabledDidChange, object: harness.audio, queue: nil) { _ in - posts += 1 - } - defer { NotificationCenter.default.removeObserver(observer) } harness.audio.musicEnabled = false - harness.audio.savedDataDidSync([harness.audio.configuration.settings.soundKey]) - harness.audio.savedDataDidSync([harness.audio.configuration.settings.musicKey]) - #expect(posts == 2) - // A new configuration may read the switch under another key. - harness.audio.configure(harness.audio.configuration) - #expect(posts == 3) + #expect(harness.backend.track == nil) + harness.audio.musicEnabled = true + #expect(harness.backend.track == "Menu") } @Test func aNewBackendGetsTheSoundsAndTheTrack() { diff --git a/README.md b/README.md index a13bdf11..2a6d4100 100644 --- a/README.md +++ b/README.md @@ -413,13 +413,12 @@ another crossfades in, nil fades out), `stopMusic`, `pauseMusic`, `AudioManager.isSoundEnabled` and `isMusicEnabled` are the settings' switches, saved under `settings.soundEnabled` and `settings.musicEnabled` unless the configuration says otherwise, and `savedDataDidSync(_:)` follows -another device's (posting `musicEnabledDidChange`). Other apps' audio never -silences the soundtrack: on Apple platforms the session is ambient, so the -player's own music mixes in and only calls, Siri and alarms interrupt (the -soundtrack comes back as they end, or as the app is next active); on Android -the game takes audio focus each time it comes to the front while its music -is on (`AndroidPlatformServices.Audio`, `.manager(_:)`), and calls reach -`audioFocusDidChange(interrupted:)`. Whatever a backend can't do (a voice of +another device's. Only that switch silences the soundtrack: it mixes with +other apps' audio, the player's own music included, which plays on (an +ambient session on Apple platforms, no audio focus on Android). On Apple +platforms the system still silences every app for a call, Siri or an alarm; +the soundtrack comes back as it ends, or at the latest as the app is next +active. Whatever a backend can't do (a voice of its own, on a backend without them) falls back to playing the sound once. ### Sprites, text and scenes (`PlatformSprite`) @@ -631,7 +630,7 @@ leaves the front, synchronized as it comes back), Play Billing or simulated purchases to its store. Play Games needs the mapping packed in the APK (`PlayGamesMapping.bundled()`); without it achievements and saved data stay on the device. It also sets the device's hooks (haptics, battery saver as -Low Power Mode, audio focus, and on request the status bar, battery, +Low Power Mode, and on request the status bar, battery, connection and image codecs). Its sources are all `SPRITEKIT_SHIM`, so Apple builds compile it empty. @@ -646,10 +645,10 @@ scene sized to `sceneSize(for:)` then `didLayout(_:)`, `didAppear`, `captureFrame`, `debugSummary`), `AudioManager.shared` (`useAudio`), `-FixedFrameStep` in a debug build (`0.0333` or `1/30`), and `DisplaySettingsHost`; Back, keys and links go untaken until the game writes its own. -`AndroidPlatformServices.Configuration.toolkit(gameCenter:syncsSavedData:store:audio:)` +`AndroidPlatformServices.Configuration.toolkit(gameCenter:syncsSavedData:store:statusBar:)` hands the toolkit's managers their Play backends (achievements and leaderboards, Saved Games under `ICloudSyncManager`, Play Billing for the -store's products, audio focus), and `DisplaySettings.Configuration +store's products, the status bar), and `DisplaySettings.Configuration .withLaunchSplash` keeps Auto from measuring the splash and reads `-RenderScale`. ### Input: focus, gamepads, keys (`PlatformInput`) diff --git a/Templates/App/README.md b/Templates/App/README.md index 80283bb0..9c1ff7ea 100644 --- a/Templates/App/README.md +++ b/Templates/App/README.md @@ -34,8 +34,7 @@ them changes only its imports. | --- | --- | --- | | `spritekit` | `SpriteKitActivity` | SDL's activity: launch arguments in debuggable builds, the game's orientations (`OrientationPolicy`, + its test), the environment the runtime reads (below), Back on Android 13 and later, the safe area as iOS gives it, links (`gameLink`, held until the shell can take them, a cold start's as `-LaunchLink`), the share sheet (`shareFile`), Paste over a text field (`offerPaste`), the platform channel's JNI | | | `PlatformServices`, `PlatformService` | The channel's Java end: a registry of services by name, dispatching `service.method` calls and queueing events (`post`) | -| | `DeviceServices` | `device`: haptics, battery saver, audio focus, the status bar, the app's settings page (`openAppSettings`), the battery (`battery`), the connection (`connection`, with the app's `ACCESS_NETWORK_STATE`), JPEG and PNG re-encoding (`jpegToPng`, `pngToJpeg`) | -| | `AudioFocusPolicy` (+ its test) | When to ask for audio focus and give it up: each time the game comes to the front while its music is on | +| | `DeviceServices` | `device`: haptics, battery saver, the status bar, the app's settings page (`openAppSettings`), the battery (`battery`), the connection (`connection`, with the app's `ACCESS_NETWORK_STATE`), JPEG and PNG re-encoding (`jpegToPng`, `pngToJpeg`) | | | `PlayGamesServices` (+ `ScorePagingTest`) | `games`: sign-in, achievements, leaderboards (submitting, loading them and their scores, showing them at a time span and collection), the player, Saved Games | | | `PlayReview` | `review`: Play In-App Review, behind `SKStoreReviewController` | | `spritekit-billing` | `PlayBilling` | `billing`: one-time products (prices, purchases, acknowledgement, restore) and consumables (`consume`, each purchase's `quantity`) |