Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle mediaServicesWereReset Notification #956

Merged
merged 1 commit into from
Jul 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 1 addition & 6 deletions BookPlayer/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate {

try? AVAudioSession.sharedInstance().setCategory(
AVAudioSession.Category.playback,
mode: AVAudioSession.Mode(rawValue: convertFromAVAudioSessionMode(AVAudioSession.Mode.spokenAudio)),
mode: .spokenAudio,
options: []
)

Expand Down Expand Up @@ -475,8 +475,3 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
}
}
}

// Helper function inserted by Swift 4.2 migrator.
private func convertFromAVAudioSessionMode(_ input: AVAudioSession.Mode) -> String {
return input.rawValue
}
72 changes: 56 additions & 16 deletions BookPlayer/Player/PlayerManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ final class PlayerManager: NSObject, PlayerManagerProtocol {

private var fadeTimer: Timer?

private var timeControlPassthroughPublisher = CurrentValueSubject<AVPlayer.TimeControlStatus, Never>(.paused)
private var timeControlSubscription: AnyCancellable?
private var playableChapterSubscription: AnyCancellable?
private var isPlayingSubscription: AnyCancellable?
private var periodicTimeObserver: Any?
Expand Down Expand Up @@ -97,17 +99,32 @@ final class PlayerManager: NSObject, PlayerManagerProtocol {
self.userActivityManager = UserActivityManager(libraryService: libraryService)
super.init()

self.setupPlayerInstance()
setupPlayerInstance()

NotificationCenter.default.addObserver(self,
selector: #selector(playerDidFinishPlaying(_:)),
name: .AVPlayerItemDidPlayToEndTime,
object: nil)
NotificationCenter.default.addObserver(
self,
selector: #selector(playerDidFinishPlaying(_:)),
name: .AVPlayerItemDidPlayToEndTime,
object: nil
)

NotificationCenter.default.addObserver(
self,
selector: #selector(handleMediaServicesWereReset),
name: AVAudioSession.mediaServicesWereResetNotification,
object: nil
)
}

func setupPlayerInstance() {
if let observer = periodicTimeObserver {
audioPlayer.removeTimeObserver(observer)
}

audioPlayer = AVPlayer()

let interval = CMTime(seconds: 1.0, preferredTimescale: CMTimeScale(NSEC_PER_SEC))
self.periodicTimeObserver = self.audioPlayer.addPeriodicTimeObserver(
periodicTimeObserver = audioPlayer.addPeriodicTimeObserver(
forInterval: interval,
queue: DispatchQueue.main
) { [weak self] _ in
Expand All @@ -117,7 +134,9 @@ final class PlayerManager: NSObject, PlayerManagerProtocol {
}

// Only route audio for AirPlay
self.audioPlayer.allowsExternalPlayback = false
audioPlayer.allowsExternalPlayback = false

bindTimeControlPassthroughPublisher()
}

func currentItemPublisher() -> AnyPublisher<PlayableItem?, Never> {
Expand Down Expand Up @@ -216,13 +235,8 @@ final class PlayerManager: NSObject, PlayerManagerProtocol {
loadChapterTask?.cancel()

// Recover in case of failure
if self.audioPlayer.status == .failed {
if let observer = self.periodicTimeObserver {
self.audioPlayer.removeTimeObserver(observer)
}

self.audioPlayer = AVPlayer()
self.setupPlayerInstance()
if audioPlayer.status == .failed {
setupPlayerInstance()
}

// Preload item
Expand Down Expand Up @@ -383,9 +397,19 @@ final class PlayerManager: NSObject, PlayerManagerProtocol {
return self.audioPlayer.timeControlStatus == .playing
}

/// We need an intermediate publisher for the `timeControlStatus`, as the `AVPlayer` instance can be recreated,
/// thus invalidating the registered observers for `isPlaying`
func bindTimeControlPassthroughPublisher() {
timeControlSubscription?.cancel()
timeControlSubscription = audioPlayer.publisher(for: \.timeControlStatus)
.sink { [weak self] timeControlStatus in
self?.timeControlPassthroughPublisher.send(timeControlStatus)
}
}

func bindPauseObserver() {
self.isPlayingSubscription?.cancel()
self.isPlayingSubscription = self.audioPlayer.publisher(for: \.timeControlStatus)
self.isPlayingSubscription = timeControlPassthroughPublisher
.delay(for: .seconds(0.1), scheduler: RunLoop.main, options: .none)
.sink { timeControlStatus in
if timeControlStatus == .paused {
Expand All @@ -397,7 +421,7 @@ final class PlayerManager: NSObject, PlayerManagerProtocol {

func isPlayingPublisher() -> AnyPublisher<Bool, Never> {
return Publishers.CombineLatest3(
audioPlayer.publisher(for: \.timeControlStatus),
timeControlPassthroughPublisher,
$playbackQueued,
$isFetchingRemoteURL
)
Expand Down Expand Up @@ -857,6 +881,22 @@ extension PlayerManager {
private func loadAndRefreshURL(item: PlayableItem) {
load(item, autoplay: playbackQueued == true, forceRefreshURL: true)
}

@objc
private func handleMediaServicesWereReset() {
/// Playback should be stopped, and wait for the user to activate it again
if isPlaying {
stopPlayback()
}

try? AVAudioSession.sharedInstance().setCategory(
AVAudioSession.Category.playback,
mode: .spokenAudio,
options: []
)

setupPlayerInstance()
}
}

// MARK: - BookMarks
Expand Down