Article

Playing Audio Using the Built-In Music Player

Create a media player inside your app to play audio from the user's media library.

Overview

There are many reasons to play music from the user's music library inside your app. For example, you might want users to listen to their own music while playing a particular level in your game. Use the built-in music player to quickly play audio tracks from the user's music library while your app is running.

Create a Media Player

Playback of the user's music requires an MPMusicPlayerController object. After importing the Media Player framework into your source file, create an appropriate player object, enqueue the music you want to play, and call the play() method. For example, the following code creates an application player object that enqueues all of the user's songs for playback.

// Get the music player.
let musicPlayer = MPMusicPlayerApplicationController.applicationQueuePlayer
// Add a playback queue containing all songs on the device.
musicPlayer.setQueue(with: .songs())
// Start playing from the beginning of the queue.
musicPlayer.play()

Your app's Info.plist file must include the NSAppleMusicUsageDescription key prior to executing this code. If that key is not present, executing the preceding code will cause your app to exit.

See Also

Built-In Music Playback

class MPMusicPlayerController

An object used to play audio media items from the device's Music app library.

protocol MPMediaPlayback

A protocol that defines the interface for controlling audio media playback.

protocol MPSystemMusicPlayerController

A protocol for playing videos in the Music app.