Overview
Let’s say you have created an app and you want users to be able to access the apple music from your app. Yes, that is possible!!
Today, we will learn how to handle apple music action using our own application like Play, Pause, Remaining time, Total time, Elapsed time, etc. with album art. In short, learn to use all Apple music actions(Next, Previous) using our own created application.
What is System Music Player?
The system music player uses the built-in Music app on your behalf. On instantiation, it takes on the current Music app state, such as the identification of the now-playing item. If a user happens to switch away from your app while the music is still playing, that music will continue playing. The Music app then has your music player’s almost every detail such as most recently-set repeat mode, shuffle mode, playback state, and now-playing item.
Design
Code explained
Code Topics
- Creating Outlets
- Import Framework
- Permission added in infoPlist file
- Actions for Play, Pause, Next, Previous button
Creating Outlets
@IBOutlet var imageAlbum: UIImageView! // display dong profile image @IBOutlet var lblTitle: UILabel! // display artist name and song name @IBOutlet var lblDuration: UILabel! // display total song duration @IBOutlet var lblElapsed: UILabel! // display elapsed time @IBOutlet var lblRemaining: UILabel! // display remaining time
Import Framework
First, you’ll need to import media framework
import MediaPlayer
Create a variable for the media player and timer
let audioPlayer = MPMusicPlayerController.systemMusicPlayer var timer = Timer()
Permission added in infoPlist file
Now set the permission to access the Apple Music. And set in info.plist
<key>NSAppleEventsUsageDescription</key>
Next we’ll need to add some code to the viewDidLoad function to get things going at startup, starting with getting the media player ready to go:
audioPlayer.prepareToPlay()
Next, you’ll need to set up the timer, this will come in the handle when a song is playing.
self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.timerFired(_:)), userInfo: nil, repeats: true)
Actions for Play, Pause, Next, Previous button
We create some actions for play, pause, next and previous music.
@IBAction func btnNextTapped(_ sender: UIButton) { audioPlayer.skipToNextItem() }
@IBAction func btnPreviousTapped(_ sender: UIButton) { audioPlayer.skipToPreviousItem() }
@IBAction func btnPlayPauseTapped(_ sender: UIButton) { btnPlayPauseUpdate() } func btnPlayPauseUpdate() { btnPlayPause.isSelected = !btnPlayPause.isSelected btnPlayPauseType = btnPlayPause.isSelected ? .play : .pause btnPlayPauseType == .play ? startTimer() : stopTimer() btnPlayPauseType == .play ? audioPlayer.play() : audioPlayer.pause() }
Inside that function is where we are going to update all of the labels as well as get the slider to progress along with the song. Enter the following in the function:
if let currentTrack = MPMusicPlayerController.systemMusicPlayer.nowPlayingItem { }
This creates a constant for
MPMusicPlayerController.systemMusicPlayer().nowPlayingItem
so it’s easier to call while also ensuring that it exists before trying to pull the information. We’re going to need to pull a few key things before we can do anything, and the code should be pretty self-explanatory.
let trackArtist = currentTrack.artist ?? "" let albumImage = currentTrack.artwork?.image(at: imageAlbum.bounds.size) let trackDuration = currentTrack.playbackDuration let trackElapsed = audioPlayer.currentPlaybackTime
Now we set the timer’s interval to 1, the information will be updated every 1 second, so the currentPlaybackTime will constantly update as the song plays.
So what do we do with that information? First, let’s go ahead and set the image to the current track’s album artwork, which we’ve already gotten above.
imageAlbum.image = albumImage
We can also set the label above the slider to display the song’s artist and title.
lblTitle.text = "\(trackArtist) - \(trackName)"
Now calculate the total duration of song.
let trackDuration = currentTrack.playbackDuration //Convert total seconds into minutes let trackDurationMinutes = Int(trackDuration / 60) //get last remaining seconds let trackDurationSeconds = trackDuration.truncatingRemainder(dividingBy: 60) //convert second into integer let trackDurationInt = Int(trackDurationSeconds) //display total duration of song lblDuration.text = "Length:\(trackDurationMinutes):\(trackDurationInt)"
In Next step calculate the remaining and elapsed time.
// get current playback time let trackElapsed = audioPlayer.currentPlaybackTime
// convert into minutes and get remaining seconds let trackElapsedMinutes = Int(trackElapsed / 60) //get last remaining seconds let trackElapsedSeconds = trackElapsed.truncatingRemainder(dividingBy: 60) // Convert into integer track elapsed time let trackElapsedInt = Int(trackElapsedSeconds) // Display elapsed time lblElapsed.text = "Elapsed: \(trackElapsedMinutes):\(trackElapsedInt)"
// calculate last remaining minutes and seconds let trackRemaining = Int(trackDuration) - Int(trackElapsed) let trackRemainingMinutes = trackRemaining / 60 let trackRemainingSeconds = trackRemaining % 60 // Display remaining time lblRemaining.text = "Remaining: \(trackRemainingMinutes):\(trackRemainingSeconds)"
Now run the application and test how it works.
Conclusion
Thus this is how easy it is to have all the apple music controls in your own app. Write back for any queries. Adios!