Bradass
Bradass

Reputation: 99

Spotify SDK in Swift 3.0: how to know when a song ends

I'm building a personal app in Swift using the Spotify api, and one thing that it needs to do is to play another song once the song that was playing is over. I have the ids to the songs all ordered the way I want them to be, and I can play them successfully.

I just need to know if there's a way to tell when a song is at its end so I know when to start playing the next one or to do other things (I make a HTTP request every time a song ends for another reason).

Any suggestions or any resources you could point me to is incredibly helpful! Couldn't find an answer through google searches :(

Spotify API: Is there a way to determine when a song has finished playing?

This is a similar question that was posted but it was for javascript and it was never answered.

Upvotes: 1

Views: 859

Answers (1)

Samantha
Samantha

Reputation: 2289

You can implement the SPTAudioStreamingPlaybackDelegate protocol, set the Spotify player's playbackDelegate property and implement didStopPlayingTrack. An example class would look something like this:

class MyClass: NSObject, SPTAudioStreamingPlaybackDelegate {
    var player = SPTAudioStreamingController.sharedInstance()


    func setup() {         // Whatever function does the setup.
        player?.playbackDelegate = self
    }

    func audioStreaming(_ audioStreaming: SPTAudioStreamingController!, didStopPlayingTrack trackUri: String!) {
        playNextSong()      // Or whatever else you wish to do here.
    }

    func playNextSong() {
        // ...
    }
}

(Note that the setup function could be anything--such as viewDidLoad if the object observing the player is a view controller rather than subclassing NSObject.)

Because didStopPlayingTrack is a delegate function, the Spotify SDK should manage when it gets called (more specifically, the player should call it on its delegate object)--you don't need to call it yourself as long as the player's delegate is set.

Upvotes: 4

Related Questions