Swift AVPlayer 如何在音频结束时自动停止

Swift AVPlayer How To Stop Automatically When Audio Finished

我在 Swift 中创建了一个按钮来使用 AVPlayer 播放音频(从 link 流式传输)。如何在音频时间结束后自动停止音频?

这是我的一些代码:

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

例如,在这个URL(https://cdn.islamic.network/quran/audio/128/ar.alafasy/162.mp3)中,音频长度为19秒。所以在我播放音频 19 秒后,音频必须停止。

谢谢:)

您可以使用 NSNotificationCenter 观察器

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

    player?.play()

并在此函数中停止播放器

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