我正在尝试构建音乐应用。音乐播放完美,但音乐结束后不播放下一首歌。我正在寻找这个解决方案。当我尝试一些解决方案是给我错误。
由于未捕获的异常'NSInvalidArgumentException'而导致应用程序停止, 理由:' - [Shironamhin.MusicPlayer playerDidFinishPlaying:]: 无法识别的选择器发送到实例0x17003d960
我正在尝试这种方式
class MusicPlayer: NSObject {
static let player = MusicPlayer()
//this is global variable
var player : AVPlayer?
var playerItem:AVPlayerItem?
func initPlayer(){
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().overrideOutputAudioPort(AVAudioSessionPortOverride.speaker)
print("AVAudioSession Category Playback OK")
do {
try AVAudioSession.sharedInstance().setActive(true)
print("AVAudioSession is Active")
} catch let error as NSError {
print(error.localizedDescription)
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
func playMusic(_ musicUrl: String?) {
if let mm = musicUrl {
var url: URL!
url = URL(string: mm)
playerItem = AVPlayerItem(url: url)
player = AVPlayer(playerItem: playerItem)
player?.volume = 1.0
player?.rate = 1.0
player?.play()
NotificationCenter.default.addObserver(self, selector: Selector(("playerDidFinishPlaying:")), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem)
}
func playerDidFinishPlaying(note: NSNotification) {
print("call")
}
}
}
另外我如何实现这个playerDidFinishPlaying ??
答案 0 :(得分:0)
自Swift 3起,您必须声明Selectors
,如下所示:#selector(playerDidFinishPlaying(email:))
自Swift 4起,您必须将@objc
属性添加到该函数中:
@objc func audioDidFinishPlaying(note: NSNotification) {
print("call")
}
顺便说一句,AVAudioPlayerDelegate
有一个很好的功能:optional func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool)
,它可能更容易使用它。 :)
答案 1 :(得分:0)
我同意@ user6603599,这就是我使用的。
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
print("\naudioPlayerDidFinishPlaying")
}
确保您的MusicPlayer类设置如下:
类MusicPlayer:AVAudioPlayerDelegate {