Create a media player inside your app to play audio from the user's media library.
Framework
- Media Player
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.
Note
To follow these steps, you must have a provisioned iOS device. Simulator has no access to a device's music library.
Create a Media Player
Playback of the user's music requires an MPMusic
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
file must include the NSApple
key prior to executing this code. If that key is not present, executing the preceding code will cause your app to exit.