迅速.AVPlayer.歌曲播放完毕后如何追踪?

Meg*_*lik 25 ios avplayer swift

什么是东方方式跟踪歌曲在Swift中播放AVPlayer的时候?

是否有任何在avplayer完成播放时调用的函数,或者我应该将计时器与avplayer类引用结合起来?

Jer*_*ner 60

像这样的东西有效:

func play(url: NSURL) {
    let item = AVPlayerItem(URL: url)

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

    let player = AVPlayer(playerItem: item)
    player.play()
}

func playerDidFinishPlaying(note: NSNotification) {
    // Your code here
}
Run Code Online (Sandbox Code Playgroud)

当你完成(或进入deinit)时,不要忘记删除观察者!


Fli*_*imm 12

您需要创建一个实现AVAudioPlayerDelegate协议的对象,并将其用作AVAudioPlayer对象的委托.然后将它们链接在一起,例如:

audioPlayer = try! AVAudioPlayer(contentsOf: audioFileUrl)
audioPlayer.delegate = self
Run Code Online (Sandbox Code Playgroud)

委托可以实现响应某些事件的方法.音频播放完毕后会触发此消息:

func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

  • @Flimm他正在使用AVPlayer而不是AVAudioPlayer (9认同)

Ajh*_*lam 8

对于Swift 4.2

func play(url: URL) {
    let item = AVPlayerItem(url: url)
    NotificationCenter.default.addObserver(self, selector: #selector(self.playerDidFinishPlaying(sender:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: item)

    let player = AVPlayer(playerItem: item)
    player.play() 
}

@objc func playerDidFinishPlaying(sender: Notification) {
    // Your code here
}
Run Code Online (Sandbox Code Playgroud)


Mik*_*ter 7

Swift 3的另一个版本

NotificationCenter.default.addObserver(self, selector: #selector(self.playerDidFinishPlaying(sender:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: item)

func playerDidFinishPlaying(sender: Notification) {

    // Do Something
}
Run Code Online (Sandbox Code Playgroud)


小智 5

import AVFoundation

var AVPlayerCustom:AVAudioPlayer = AVAudioPlayer()


class PlayerModule: NSObject, AVAudioPlayerDelegate {

    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        print("Finish")
    }

    func playWithData(data: Data, proc: Int) {
        //print(data)

        do {

            AVPlayerCustom = try AVAudioPlayer(data: data)

            AVPlayerCustom.delegate = self as! AVAudioPlayerDelegate

            AVPlayerCustom.prepareToPlay()
            AVPlayerCustom.play()


        }
        catch {
            print("error1")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)