当歌曲在Swift游乐场玩完时,我试图调用一个函数。这是我使用的代码:
NotificationCenter.default.addObserver(self, selector: Selector(("playerDidFinishPlaying:")), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: winMusic)
然而,当歌曲结束播放时,该功能未被调用,我不知道为什么?它显然与iOS应用程序不同。
var winMusic = NSURL(fileURLWithPath: Bundle.main.path(forResource: "win", ofType: "mp3")!)
var winPlayer: AVAudioPlayer? = nil
class Responder : NSObject {
func playerDidFinishPlaying() {
print("test")
/* Nothing printed here */
}
func action(sender: UIButton) {
NotificationCenter.default.addObserver(self, selector: #selector(Responder.playerDidFinishPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: winMusic)
NotificationCenter.default.post(name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
winPlayer!.play()
}
}
答案 0 :(得分:1)
AVAudioPlayer不发布AVPlayerItemDidPlayToEndTime通知。你需要给玩家一个代表。见https://developer.apple.com/reference/avfoundation/avaudioplayerdelegate/1389160-audioplayerdidfinishplaying
答案 1 :(得分:0)
将winPlayer
代表设为,
winPlayer?.delegate = self
并实施方法
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
if flag == true {
// song finished successfully here
}
}
您将委托代表由您决定。