如何多次使用audioPlayerDidFinishPlaying

时间:2017-02-12 08:21:09

标签: ios swift avplayer

我在MainStoryBoard上创建了带有图像的UIButton。当我按下该按钮时,它会播放音频文件,而当音频正在播放时,UIButton的背景颜色会发生变化。

audioPlayerDidFinishPlaying1被正确调用,但似乎没有调用audioPlayerDidFinishPlaying2。我感谢任何建议,让我解决这个问题。

    let url1 = Bundle.main.bundleURL.appendingPathComponent("music1.mp3")
    let url2 = Bundle.main.bundleURL.appendingPathComponent("music2.mp3")

    @IBOutlet weak var yourButton: CustomButton!
    @IBOutlet weak var yourButton2: CustomButton! 

   func Player(url: URL) {
        do {
            try player = AVAudioPlayer(contentsOf:url)
            player.play()
            yourButton.isSelected = true
            player.delegate = self
        } catch {
            print(error)
        }
    }

    func Player1(url: URL) {
        do {
            try player = AVAudioPlayer(contentsOf:url)
            player.play()
            yourButton2.isSelected = true
            player.delegate = self
        } catch {
            print(error)
        }
    }
    @IBAction func pushButton1(sender: UIButton) {
        Player(url: url1)
    }
    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        yourButton.isSelected = false

    }

    @IBAction func pushButton2(sender: UIButton) {
        Player1(url: url2)
    }
    func audioPlayerDidFinishPlaying2(_ player: AVAudioPlayer, successfully flag: Bool) {
        yourButton2.isSelected = false
    }

1 个答案:

答案 0 :(得分:1)

您正在Player1/Player方法中本地创建播放器。所以当方法结束时,玩家将被解除分配。将生成的播放器保持为类成员,以便在方法退出时不会取消分配

在你的班级中添加:

class YourClass
{
    let url1 = Bundle.main.bundleURL.appendingPathComponent("music1.mp3")
    let url2 = Bundle.main.bundleURL.appendingPathComponent("music2.mp3")

    @IBOutlet weak var yourButton: CustomButton!
    @IBOutlet weak var yourButton2: CustomButton! 

    fileprivate var player1: AVAudioPlayer? 
    fileprivate var player2: AVAudioPlayer?

    .
    .
    .

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

另一件事......您正在使用委托方法audioPlayerDidFinishPlaying,它是AVAudioPlayer的委托方法。但audioPlayerDidFinishPlaying2并非如此,在这里没用。由于你有两个玩家,一个班级作为代表,你需要确定哪个玩家已经完成并更改了正确的按钮。

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