Home > Mobile >  Swift AVPlayer How To Stop Automatically When Audio Finished
Swift AVPlayer How To Stop Automatically When Audio Finished

Time:05-14

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 :)

CodePudding user response:

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)
    }
  • Related