How to detect the end of a song in MusicKit?
Asked Answered
H

0

6

I am attempting to use Apple's Music Kit within my application to listen to music. My issue is that the first song that plays will continually repeat. The first song plays correctly by using the following code:

let mediaArray = [songsApple?[songNumber!]] 
let playableColledction = MPMediaItemCollection.init(items: mediaArray as! [MPMediaItem]) 

applicationMusicPlayer.setQueue(with: playableCollection) 
applicationMusicPlayer.play() 
self.activateAudioSession 

The activateAudioSession method is:

 do {
   try audioSession.setCategory(AVAudioSessionCategoryPlayback) 
   try audioSession.setActive(true) 
 }
 catch let error {
   print(error.localizedDescription) 
 } 

To detect the end of the song, I use the following observer from the Apple Music Documentation:

applicationMusicPlayer.beginGeneratingPlaybackNotications() 

NotificationCenter.default.addObserver(self, #selector(didFinishSong), name: Notification.Name.MPMusicPlayerControllerNowPlayingItemDidChange, object: nil) 

The didFinishSong method is used to get the songNumber of the next song to be played from the songsApple array. This information is then passed back into the method that plays the song to get the mediaArray. However, right now, didFinishSong does not get called when the song playing finishes and instead the song just repeats from the beginning.

Is there something that I am doing wrong for detecting the end of a song? Is there another way to do it? I also tried to use a timer, but for some reason it would stop counting whenever the application entered the background making the count inaccurate.

Thank you in advance for any help that you are able to provide. If you need additional information please to not hesitate to ask and I will clarify more.

Hexateuch answered 20/6, 2018 at 18:8 Comment(1)
Hey this is off topic but could I ask how you generate the developer token? I've tried everything but I keep getting unauthorised. It looks like you've managed to do it though!Taxis

© 2022 - 2024 — McMap. All rights reserved.