2017-09-25 65 views
0
class myClass: AVAudioPlayerDelegate{ 
    var player = AVAudioPlayer() 

    init(){ 
     player.delegate = self 
    } 

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

我正在学习Swift并试图制作一个音乐播放应用程序。我有自定义类,其AVAudioPlayer对象称为播放器作为其属性。我怎样才能用AVAudioPlayerDelegate方法与玩家对象?Swift如何在不继承AVAudioPlayer的类上使用AVAudioPlayerDelegate?

当具有这样的代码我得到的错误:

从NSObject的

The type myClass does not conform to the protocol NSObjectProtocol

+0

的可能的复制[等级不符合NSObjectProtocol(https://stackoverflow.com/questions/40705591/class-does-not-conform-nsobjectprotocol) –

回答

1

继承。

class myClass: NSObject, AVAudioPlayerDelegate { 
    var player = AVAudioPlayer() 

    init(){ 
     player.delegate = self 
    } 

    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { 
      print("The song ended") 
    } 
} 
+0

我得到EXC_BAD_ACCESS崩溃的player.delegate =自我行 – Adam

+1

那么,我想这是一个完全不同的问题。问另一个问题。我忍不住,对不起。我的猜测是AVAudioPlayer在设置委托之前需要播放一些文件或其他东西,或类似的东西。我已经尝试过 player = try? AVAudioPlayer.init(data:Data.init()),现在它不会崩溃。我的猜测是正确的。添加有效的数据进行处理并且不发生错误。 –

+0

考虑接受答案,如果它解决了你的问题。 –