ios - 如何跟踪歌曲在 AVPlayer 中播放完毕的时间?

标签 ios swift swift3 avplayer nsnotificationcenter

我正在使用 swift 3.0 开发一个项目,我可以通过 AVPlayer 播放歌曲。我的要求是在歌曲播放完毕后跟踪该点并相应地更新播放按钮图像。为此,我使用了一个 NSNotification 实例。出于某种原因,它抛出一个错误

"Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Project.ViewController finishedPlaying:]: unrecognized selector sent to instance 0x7fda8e928170'".

我在这里错过了什么??我的代码如下。

 @IBAction func playButtonPressed(_ sender: Any) {

    if newRowSelected == true{
        if(isNewPathSelected){
            print("player")
            let url:URL = savePath!
            playerItem = AVPlayerItem(url: url as URL)
            player=AVPlayer(playerItem: playerItem!)
            let playerLayer=AVPlayerLayer(player: player!)
            playerLayer.frame = CGRect(x: 0, y: 0, width: 10, height: 50) // actually this player layer is not visible
            self.view.layer.addSublayer(playerLayer)
            isNewPathSelected = false
        }

        if player?.rate == 0 // this means if its not playing
        {
            print("Playing")
            player!.play()
            playButton.setImage(UIImage(named: "pause_button"), for: UIControlState.normal)

            trackTime()

            if playerItem != nil {
                print("playerItem")
                NotificationCenter.default.addObserver(self, selector: Selector(("finishedPlaying:")), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem)

            }

        } else {
            player!.pause()
            playButton.setImage(UIImage(named: "play_button"), for: UIControlState.normal)
        }
    }else{
        showAlert()
    }

}

func finishedPlaying(myNotification:NSNotification) {
    playButton.setImage(UIImage(named: "play_button"), for: UIControlState.normal)

    let stopedPlayerItem: AVPlayerItem = myNotification.object as! AVPlayerItem
    stopedPlayerItem.seek(to: kCMTimeZero)
}

最佳答案

改变你的通知观察者

 NotificationCenter.default.addObserver(self, selector: Selector(("finishedPlaying:")), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem)

进入swift3语法

  NotificationCenter.default.addObserver(self, selector: #selector(self.finishedPlaying(_:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem)

并将方法调用为

@objc func finishedPlaying( _ myNotification:NSNotification) {

}

关于ios - 如何跟踪歌曲在 AVPlayer 中播放完毕的时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44152949/

相关文章:

ios - 在没有 SKAction.Sequence 的情况下按顺序运行两个 SKActions(确保一个完成,等待然后运行另一个)

ios - 在用户交互中快速停止 ScrollView 中的自动滚动

swift - 如何在 Swift 3 的 TableView Cell 中设置具有更高值 t 的右上角半径

android - 蓝牙低功耗: Read Long Characteristics Value using Android/iOS

ios - Swift 自定义单元格布局 TableView 决策

uitableview - 我无法让我的 UITableView 快速重新加载数据

database - 如何使用swift 3在核心数据中只获取一列数据

ios - 导致错误的 Swift 3 更新

ios - 如何使用 Swift 将文本复制到剪贴板/粘贴板

iOS- SQLITE_MISUSE 错误(代码 21)