我正在为测试项目创建示例播放器。我创建了一个NSNotification来调用一个函数来播放数组中的下一个音轨。问题是通知连续约8次调用此函数?我不知道为什么会这样。这是我的代码,感谢您的帮助!

let player = AVPlayer()

var urlPlayerItems = [String]()

var currentTrack: Int = 0



    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        // Checks to see if player reached end
        NotificationCenter.default.addObserver(self,
                                                    selector: #selector(PlayerViewController.autoplayNextTrack(notification:)),
                                                    name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
                                                    object: player.currentItem)

}

    func playTrack() {

        if urlPlayerItems.count > 0 {
            let newMovieURL = URL(string: urlPlayerItems[currentTrack])!
            asset = AVURLAsset(url: newMovieURL, options: nil)

            player.play()
        }
    }



    func autoplayNextTrack(notefication: NSNotification) {
        if (currentTrack + 1) >= urlPlayerItems.count {
            currentTrack = 0
        } else {
            currentTrack += 1
        }
        playTrack()
    }

最佳答案

除了不应多次设置观察者这一事实之外,我认为您应该在再次调用播放功能之前将播放器重置为零。

func autoplayNextTrack(notefication: NSNotification) {
    player.seekToTime(kCMTimeZero)
    if (currentTrack + 1) >= urlPlayerItems.count {
        currentTrack = 0
    } else {
        currentTrack += 1
    }

    playTrack()
}

09-04 14:05