How to multiple play() in audioPlayerDidFinishPlaying method

北战南征 提交于 2019-12-02 04:44:33

Don't use this 3 different in VC

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

Instead of this use only one of this in AppDelegate and access it from your VC so you won't have same issue. When next audio will play previous audio will stop

Use this in App delegate:

var player1:AVAudioPlayer?

Again in your VC use this instance

func Player1(url: URL) {
            do {
 let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
                try appDelegate.player1 = AVAudioPlayer(contentsOf:url)
                appDelegate.player1!.play()
                yourButton2.isSelected = true
                appDelegate.player1!.delegate = self

            } catch {
                print(error)
            }
        }

You are playing all at the same time, there is no delay or nothing waiting for the previous to finish.

Your class should become the delegate of the AVAudioPlayer, so you first play the first audio file and once you get the delegate call audioPlayerDidFinishPlaying:successfully: you play the next one.

You should modify your delegate call to look something like this:

func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
            if (player === player1) {
                player2!.play()
            } else if (player === player2) {
                player3!.play()
            } else if (player === player3) {
                // You're done!
            }
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!