Skip to content
This repository has been archived by the owner on Aug 12, 2022. It is now read-only.

Add utilities for media playback #91

Merged
merged 2 commits into from
Jun 22, 2020
Merged

Conversation

mickael-menu
Copy link
Member

This PR adds utilities to simplify the playback of media files in a reading app, and the creation of an audiobook navigator.

AudioSession

Manages an activated AVAudioSession and handles interruptions (e.g. phone calls).

To use it, implements the AudioSessionUser protocol in your audio navigator or media player, to provide an AVAudioSession configuration and a play() method which will be called when an interruption is finished. Then, call AVAudioSession.start() when playing and AVAudioSession.end() when discarding the player. The underlying AVAudioSession will automatically be set up.

final class MediaPlayer: AudioSessionUser {

    deinit {
        AudioSession.shared.end(for: self)
    }

    func play() {
        AudioSession.shared.start(with: self)
        // Start audio playback...
    }

}

NowPlayingInfo

Manages the Now Playing media item displayed on the lock screen.

This provides a type-safe high-level API around MPNowPlayingInfoCenter. Changes are throttled to avoid updating the info too often.

Usage examples:

// The following functions are examples of event observers called by a media player.

/// Called frequently during playback, to update the time information.
func playbackDidChange(currentTime: Double, duration: Double, rate: Double) {
    let nowPlayingInfo = NowPlayingInfo.shared
    nowPlayingInfo.playback.duration = duration
    nowPlayingInfo.playback.elapsedTime = currentTime
    nowPlayingInfo.playback.rate = rate
}

/// Called every time the played resource changes.
func playedResourceDidChange(index: Int, in publication: Publication) {
    let link = publication.readingOrder[index]
    NowPlayingInfo.shared.media = NowPlayingInfo.Media(
        title: link.title,
        artist: publication.metadata.authors.map { $0.name }.joined(", "),
        artwork: publication.cover,
        chapterCount: publication.readingOrder.count,
        chapterNumber: index + 1
    )
}

/// Called when we're done playing this publication.
func navigatorDidClose() {
    // Resets the Now Playing screen.
    NowPlayingInfo.shared.clear()
}

@mickael-menu mickael-menu merged commit 41c9fdd into develop Jun 22, 2020
@mickael-menu mickael-menu deleted the feature/audiobook+format branch June 22, 2020 13:12
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant