diff --git a/AGENTS.md b/AGENTS.md index 14d4dd1e..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. -- 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: 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 769a3a09..00000000 --- a/Library/spritekit/src/main/java/com/spritekit/platform/AudioFocusPolicy.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.spritekit.platform; - -/** - * When the game asks for audio focus, 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. - */ -final class AudioFocusPolicy { - /** What a resume does 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, - } - - /** Whether the game's stream is stopped: before the first start, and after a stop. */ - private boolean stopped = true; - - Step onResume(boolean holdsFocus, boolean musicActive) { - boolean afterStop = stopped; - stopped = false; - if (holdsFocus || !afterStop) return Step.KEEP; - return musicActive ? Step.OTHER_AUDIO : Step.REQUEST; - } - - /** The game went to the background: give focus up. */ - void onStop() { - stopped = true; - } -} 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..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, 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}. + *
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,11 +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; - private boolean hasFocus; - private final AudioFocusPolicy focusPolicy = new AudioFocusPolicy(); private final BroadcastReceiver powerSaveReceiver = new BroadcastReceiver() { @Override @@ -83,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) { @@ -259,30 +249,10 @@ 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; - } - } - - @Override - public void onStop() { - focusPolicy.onStop(); - abandonFocus(); } @Override public void onDestroy() { - abandonFocus(); try { activity.unregisterReceiver(powerSaveReceiver); } catch (IllegalArgumentException alreadyGone) { @@ -294,62 +264,6 @@ private void postPowerSave() { services.post(SERVICE, "powerSave", PlatformServices.object("enabled", power != null && power.isPowerSaveMode())); } - // MARK: - Audio focus - - 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()) - .setOnAudioFocusChangeListener(this) - .build(); - } - result = audio.requestAudioFocus(focusRequest); - } 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)); - } - - 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; - services.post(SERVICE, "audio", PlatformServices.object("otherAudio", false, "interrupted", false)); - break; - case AudioManager.AUDIOFOCUS_LOSS: - // Another app's music: the soundtrack steps aside for good, - // until the game next comes to the front. - abandonFocus(); - services.post(SERVICE, "audio", PlatformServices.object("otherAudio", true, "interrupted", false)); - break; - case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT: - // A call or an alarm: everything waits. - services.post(SERVICE, "audio", PlatformServices.object("otherAudio", false, "interrupted", 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 d3a3c700..00000000 --- a/Library/spritekit/src/test/java/com/spritekit/platform/AudioFocusPolicyTest.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.spritekit.platform; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class AudioFocusPolicyTest { - @Test - public void firstStartAsksForFocusWhenNothingPlays() { - AudioFocusPolicy policy = new AudioFocusPolicy(); - assertEquals(AudioFocusPolicy.Step.REQUEST, policy.onResume(false, false)); - } - - @Test - public void firstStartStepsAsideForOtherMusic() { - AudioFocusPolicy policy = new AudioFocusPolicy(); - assertEquals(AudioFocusPolicy.Step.OTHER_AUDIO, policy.onResume(false, true)); - } - - /** - * 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. - */ - @Test - public void pauseWithoutStopKeepsFocusThoughItsOwnMusicPlays() { - AudioFocusPolicy policy = new AudioFocusPolicy(); - policy.onResume(false, false); - assertEquals(AudioFocusPolicy.Step.KEEP, policy.onResume(true, true)); - } - - @Test - public void pauseWithoutStopAndNoFocusChangesNothing() { - AudioFocusPolicy policy = new AudioFocusPolicy(); - policy.onResume(false, true); - assertEquals(AudioFocusPolicy.Step.KEEP, policy.onResume(false, true)); - } - - @Test - public void backFromAStopLooksForOtherMusicAgain() { - AudioFocusPolicy policy = new AudioFocusPolicy(); - policy.onResume(false, false); - policy.onStop(); - assertEquals(AudioFocusPolicy.Step.OTHER_AUDIO, policy.onResume(false, true)); - policy.onStop(); - assertEquals(AudioFocusPolicy.Step.REQUEST, policy.onResume(false, false)); - } -} diff --git a/Platform/Sources/PlatformAndroid/AndroidPlatformServices.swift b/Platform/Sources/PlatformAndroid/AndroidPlatformServices.swift index 7d2a77bb..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? - /// 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)? /// The settings' status bar switch, shown or hidden as it changes. public var statusBar: StatusBar? /// The battery and connection a game's diagnostics read @@ -182,7 +179,6 @@ public enum AndroidPlatformServices { } } let center = configuration.notificationCenter - let audioFocusChanged = configuration.audioFocusChanged channel.on("device") { event, body in switch event { case "powerSave": @@ -191,8 +187,6 @@ public enum AndroidPlatformServices { Device.lowPowerMode = enabled // As iOS posts Low Power Mode changing. center.post(name: .NSProcessInfoPowerStateDidChange, object: nil) - case "audio": - audioFocusChanged?(body.bool("otherAudio") ?? false, body.bool("interrupted") ?? false) default: break } diff --git a/Platform/Sources/PlatformAndroidHost/ToolkitServices.swift b/Platform/Sources/PlatformAndroidHost/ToolkitServices.swift index 00fe8184..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,11 +36,6 @@ extension AndroidPlatformServices.Configuration { if let store { services.billing = .init(store: store) } - if let audio { - services.audioFocusChanged = { otherAudio, interrupted in - MainActor.assumeIsolated { audio.audioFocusDidChange(otherAudio: otherAudio, interrupted: interrupted) } - } - } if statusBar { services.statusBar = .setting } diff --git a/Platform/Sources/PlatformAudio/AppleAudioBackend.swift b/Platform/Sources/PlatformAudio/AppleAudioBackend.swift index 22f4408b..0015fef1 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. 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 - /// 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..4c503fab 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: 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 @@ -43,8 +45,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? private var sentVolume: Float = 0 @@ -81,15 +81,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,20 +89,6 @@ 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) - } - // MARK: Settings /// The settings' keys, for a game that syncs them. @@ -330,7 +307,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..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.audioFocusChanged != 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.audioFocusChanged == 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..54c6c4d2 100644 --- a/Platform/Tests/PlatformAndroidTests/PlatformAndroidTests.swift +++ b/Platform/Tests/PlatformAndroidTests/PlatformAndroidTests.swift @@ -118,16 +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 focus: (Bool, Bool)? var statusBarVisible = true let statusBarChanged = Notification.Name("test.statusBar") var config = configuration(java, center) config.playGames = nil - config.audioFocusChanged = { focus = ($0, $1) } config.diagnostics = true config.statusBar = .init(isVisible: { statusBarVisible }, changed: statusBarChanged) @@ -147,12 +145,10 @@ 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], ]) center.removeObserver(observer) #expect(!Device.lowPowerMode) #expect(powerChanges == 1) - #expect(focus.map { [$0.0, $0.1] } == [true, 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..ef61ba17 100644 --- a/Platform/Tests/PlatformAudioTests/AudioManagerTests.swift +++ b/Platform/Tests/PlatformAudioTests/AudioManagerTests.swift @@ -274,21 +274,13 @@ struct MusicTests { #expect(harness.music.last?.volume == 0.4) } - @Test func otherAudioHasTheSoundtrackStepAsideAndInterruptionsSuspend() { + @Test func onlyTheMusicSwitchSilencesTheSoundtrack() { 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) #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) + harness.audio.musicEnabled = false + #expect(harness.backend.track == nil) + harness.audio.musicEnabled = true #expect(harness.backend.track == "Menu") } diff --git a/README.md b/README.md index d238983d..2a6d4100 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,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. 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. 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`) @@ -627,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. @@ -642,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 32a8eb81..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, as an ambient iOS session behaves | +| | `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`) |