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

在Swift中用AVPlayer播放歌曲时,东方的方式是什么?

avplayer玩完了还有什么function吗,或者我应该把avplayer类的参考结合在一起?

像这样的作品:

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 } 

不要忘了在完成(或deinit )时删除观察者!

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

 audioPlayer = try! AVAudioPlayer(contentsOf: audioFileUrl) audioPlayer.delegate = self 

委托人可以实现响应某些事件的方法。 当audio播放结束时,这个会发生:

 func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { // ... } 

Swift 3的另一个版本

 NotificationCenter.default.addObserver(self, selector: #selector(self.playerDidFinishPlaying(sender:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: item) func playerDidFinishPlaying(sender: Notification) { // Do Something } 

对于Swif3,您需要更改如下:

 func play(url: NSURL) { let item = AVPlayerItem(URL: url) NotificationCenter.default.addObserver(self,selector:Selector("playerDidFinishPlaying"), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: item) let player = AVPlayer(playerItem: item) player.play() } func playerDidFinishPlaying() { // Your code here } 

更完整的解决scheme在这里:

 import UIKit import AVFoundation import MediaPlayer class ViewController: UIViewController,AVAudioPlayerDelegate { var player: AVAudioPlayer = AVAudioPlayer() @IBAction func play(_ sender: UIButton) { player.play() player.currentTime=14*60-10 print(player.currentTime) } @IBAction func pause(_ sender: UIButton) { player.pause() } @IBAction func replay(_ sender: UIButton) { player.currentTime=0 } override func viewDidLoad() { super.viewDidLoad() do{ let audioPath = Bundle.main.path(forResource: "elon", ofType: "mp3") player = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: audioPath!)) player.prepareToPlay() player.delegate = self } catch{ print(error) } } func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool){ print(flag) print("here") if flag == true{ } } } 
 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") } } }