'Swift AVPlayer How To Stop Automatically When Audio Finished

I've created a button to play audio (streaming from a link) with AVPlayer in Swift. How to stop the audio automatically when the audio time is finished?

Here is some of my code :

var player : AVPlayer?
url = URL(string: "https://cdn.islamic.network/quran/audio/128/ar.alafasy/162.mp3")
let playerItem:AVPlayerItem = AVPlayerItem(url: url!)
player = AVPlayer(playerItem: playerItem)

player?.play()

For example, in this URL (https://cdn.islamic.network/quran/audio/128/ar.alafasy/162.mp3), the audio length is 19 seconds. So after 19 seconds I play the audio, the audio must stop.

Thank you :)



Solution 1:[1]

You can use the NSNotificationCenter Observer

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

    player?.play()

and stop player in this function

    func playerDidFinishPlaying(note: NSNotification) {
        // Your code here
        player?.pause()
        player?.replaceCurrentItem(with: nil)
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jagjeet Singh