简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM