Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift. AVPlayer. How to track when song finished playing?

What is the east way to track when song finished playing with AVPlayer in Swift?

Is there any function which is called when avplayer finished playing, or I should combine timer with avplayer class references?

like image 943
Mega4alik Avatar asked Jan 06 '15 19:01

Mega4alik


4 Answers

Something like this works:

func play(url: NSURL) {
    let item = AVPlayerItem(URL: url)

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerDidFinishPlaying:", name: AVPlayerItemDidPlayToEndTimeNotification, object: item)

    let player = AVPlayer(playerItem: item)
    player.play()
}

func playerDidFinishPlaying(note: NSNotification) {
    // Your code here
}

Don't forget to remove the observer when you're done (or in deinit)!

like image 57
Jernej Strasner Avatar answered Oct 09 '22 04:10

Jernej Strasner


You need to create an object that implements the AVAudioPlayerDelegate protocol, and use that as the delegate of the AVAudioPlayer object. Then link them together, for example:

audioPlayer = try! AVAudioPlayer(contentsOf: audioFileUrl)
audioPlayer.delegate = self

The delegate can implement methods that responds to certain events. This one fires when the audio finishes playing:

func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
    // ...
}
like image 27
Flimm Avatar answered Oct 09 '22 04:10

Flimm


for Swift 4.2

func play(url: URL) {
    let item = AVPlayerItem(url: url)
    NotificationCenter.default.addObserver(self, selector: #selector(self.playerDidFinishPlaying(sender:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: item)

    let player = AVPlayer(playerItem: item)
    player.play() 
}

@objc func playerDidFinishPlaying(sender: Notification) {
    // Your code here
}
like image 20
Return Zero Avatar answered Oct 09 '22 03:10

Return Zero


Another version for Swift 3

NotificationCenter.default.addObserver(self, selector: #selector(self.playerDidFinishPlaying(sender:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: item)

func playerDidFinishPlaying(sender: Notification) {

    // Do Something
}
like image 28
Mike Carpenter Avatar answered Oct 09 '22 04:10

Mike Carpenter