MediaPlayer

The MediaPlayer API allows you to interact with the Now Playing Center, manage Now Playing Info, and respond to remote control events. Below is a comprehensive guide on its usage, including best practices and examples.


Getting Started

The MediaPlayer API provides control over media playback information and remote command handling. To get started:

  1. Set the nowPlayingInfo to display current media information.
  2. Configure available commands using setAvailableCommands().
  3. Register a commandHandler to respond to remote events.
1MediaPlayer.nowPlayingInfo = {
2  title: "Song Title",
3  artist: "Artist Name",
4  playbackRate: 1.0,
5  elapsedPlaybackTime: 30,
6  playbackDuration: 240
7}
8
9MediaPlayer.setAvailableCommands(["play", "pause", "nextTrack", "previousTrack"])
10
11MediaPlayer.commandHandler = (command, event) => {
12  console.log(`Command received: ${command}`)
13}

API Reference

NowPlayingInfo

The nowPlayingInfo object displays metadata about the currently playing media. Set it to null to clear the Now Playing Info Center.

Properties:

  • title: string (Required)
    • The title of the media item.
  • artist: string (Optional)
    • The artist or performer of the media item.
  • albumTitle: string (Optional)
    • The album title of the media item.
  • artwork: UIImage (Optional)
    • An image representing the media item.
  • mediaType: MediaType (Optional)
    • Defaults to audio.
  • playbackRate: number (Optional)
    • Defaults to 0. Indicates the current playback rate.
  • elapsedPlaybackTime: DurationInSeconds (Optional)
    • Defaults to 0. The current playback time.
  • playbackDuration: DurationInSeconds (Optional)
    • Defaults to 0. The total duration of the media.

Playback State

The playbackState property indicates the app's current playback state:

  • unknown: Default state when playback status is undefined.
  • playing: Media is actively playing.
  • paused: Media playback is paused.
  • stopped: Playback has stopped.
  • interrupted: Playback is interrupted by an external event.
1if (MediaPlayer.playbackState === MediaPlayerPlaybackState.playing) {
2    console.log("Media is currently playing")
3}

Commands and Event Handlers

setAvailableCommands(commands: MediaPlayerRemoteCommand[])

Specifies which remote commands are enabled for user interaction.

Example:

1MediaPlayer.setAvailableCommands(["play", "pause", "stop", "nextTrack"])

commandHandler

A callback to handle remote commands. Register this function to process commands like play, pause, or seekBackward.

Example:

1MediaPlayer.commandHandler = (command, event) => {
2  switch (command) {
3    case "play":
4      console.log("Play command received")
5      break
6    case "pause":
7      console.log("Pause command received")
8      break
9    default:
10      console.log(`Command not handled: ${command}`)
11  }
12}

Supported Commands:

  • play, pause, stop, nextTrack, previousTrack
  • seekBackward, seekForward, skipBackward, skipForward
  • rating, like, dislike, bookmark
  • changeRepeatMode, changeShuffleMode
  • enableLanguageOption, disableLanguageOption

Common Use Cases

Display Now Playing Info

1MediaPlayer.nowPlayingInfo = {
2  title: "Podcast Episode",
3  artist: "Podcast Host",
4  elapsedPlaybackTime: 120,
5  playbackDuration: 1800,
6  playbackRate: 1.0
7}

Respond to Playback Commands

1MediaPlayer.setAvailableCommands(["play", "pause", "stop"])
2
3MediaPlayer.commandHandler = (command, event) => {
4  if (command === "play") {
5    console.log("Start playback")
6  } else if (command === "pause") {
7    console.log("Pause playback")
8  }
9}

Handle Custom Events

1MediaPlayer.commandHandler = (command, event) => {
2  if (command === "seekForward") {
3    const seekEvent = event as MediaPlayerSeekCommandEvent
4    console.log(`Seek Event Type: ${seekEvent.type}`)
5  }
6}

Best Practices

  1. Keep Metadata Up-to-Date: Update nowPlayingInfo as playback changes.
  2. Handle All Relevant Commands: Ensure user interactions like skipping or seeking are supported.
  3. Resource Management: Clear nowPlayingInfo when playback stops to avoid stale information.
  4. Test with External Devices: Use remote controls like headphones or car systems to validate command handling.
  5. Provide Feedback: Inform users of successful or failed actions in response to commands.

Full Example

Below is a complete implementation of MediaPlayer:

1// Set Now Playing Info
2MediaPlayer.nowPlayingInfo = {
3  title: "Song Title",
4  artist: "Artist Name",
5  albumTitle: "Album Name",
6  playbackRate: 1.0,
7  elapsedPlaybackTime: 0,
8  playbackDuration: 300
9}
10
11// Enable Commands
12MediaPlayer.setAvailableCommands(["play", "pause", "nextTrack", "previousTrack", "seekForward", "seekBackward"])
13
14// Handle Commands
15MediaPlayer.commandHandler = (command, event) => {
16  switch (command) {
17    case "play":
18      console.log("Playing media")
19      break
20    case "pause":
21      console.log("Pausing media")
22      break
23    case "nextTrack":
24      console.log("Skipping to next track")
25      break
26    case "seekForward":
27      const seekEvent = event as MediaPlayerSeekCommandEvent
28      console.log(`Seek Event: ${seekEvent.type}`)
29      break
30    default:
31      console.log(`Unhandled command: ${command}`)
32  }
33}