如何在一个类中使用audioPlayerDidFinishPlaying

时间:2017-02-13 20:05:08

标签: ios swift xcode

Player1运行良好,但我在实施Player2时遇到错误。

我应该如何更改audioPlayerDidFinishPlaying以使其正常工作?

以下是我的ViewController.swift的代码:

  func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
    if (player === player2) {
        yourButton2.isSelected = false
    } else {
     yourButton.isSelected = false
        player2!.play()
        yourButton2.isSelected = false
    }
}


  func Player1(url: URL) {
    do {
        try player2 = AVAudioPlayer(contentsOf:url)
        player2!.play()
        yourButton2.isSelected = true
        player2!.delegate = self

    } catch {
        print(error)
    }
}

  func Player2(url: URL, url2: URL) {
    do {
        try player1 = AVAudioPlayer(contentsOf:url)
        try player2 = AVAudioPlayer(contentsOf: url2)
        player1!.play()
        yourButton.isSelected = true
        player1!.delegate = self
    } catch {
        print(error)
    }
}

1 个答案:

答案 0 :(得分:1)

audioPlayerdidFinishPlaying(_:successfully:)中,您有else if - 条款永远不会成为true

} else if (player === player3) {

player3 始终nil,因为您永远不会为其分配内容。因此,audioPlayerdidFinishPlaying(_:successfully:)中的第3个分支将永远不会被执行。要在当前的类设计中使其工作,您需要:

  • 更改else if子句
  • 将内容分配给player3