-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlayolaPlayerExampleApp.swift
More file actions
81 lines (72 loc) · 2.4 KB
/
Copy pathPlayolaPlayerExampleApp.swift
File metadata and controls
81 lines (72 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
//
// PlayolaPlayerExampleApp.swift
// PlayolaPlayerExample
//
// Created by Brian D Keane on 12/29/24.
//
import AVFoundation
import PlayolaPlayer
import SwiftUI
@main
struct PlayolaPlayerExampleApp: App {
private let audioSession = HostAudioSession()
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
/// PlayolaPlayer does not manage the `AVAudioSession` — the host app owns it.
/// This demonstrates the full host contract: configure + activate the session,
/// and drive `pauseForInterruption()` / `resumeAfterInterruption()` from the
/// interruption notifications. A production app would also handle route changes.
@MainActor
final class HostAudioSession {
/// Retained so the block observer can be removed in deinit and its lifetime
/// is explicit (NotificationCenter holds the token until removal).
private var interruptionObserver: (any NSObjectProtocol)?
init() {
do {
let session = AVAudioSession.sharedInstance()
try session.setCategory(.playback, mode: .default, policy: .longFormAudio, options: [])
try session.setActive(true)
} catch {
print("Failed to configure AVAudioSession: \(error)")
}
interruptionObserver = NotificationCenter.default.addObserver(
forName: AVAudioSession.interruptionNotification, object: nil, queue: .main
) { notification in
MainActor.assumeIsolated {
Self.handleInterruption(notification)
}
}
}
deinit {
if let interruptionObserver {
NotificationCenter.default.removeObserver(interruptionObserver)
}
}
private static func handleInterruption(_ notification: Notification) {
guard let typeValue = notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt,
let type = AVAudioSession.InterruptionType(rawValue: typeValue)
else { return }
switch type {
case .began:
PlayolaStationPlayer.shared.pauseForInterruption()
case .ended:
guard let optionsValue = notification.userInfo?[AVAudioSessionInterruptionOptionKey] as? UInt,
AVAudioSession.InterruptionOptions(rawValue: optionsValue).contains(.shouldResume)
else { return }
Task {
do {
try AVAudioSession.sharedInstance().setActive(true)
try await PlayolaStationPlayer.shared.resumeAfterInterruption()
} catch {
print("Resume failed: \(error)")
}
}
@unknown default:
break
}
}
}