简体   繁体   中英

How to continue to play audio after view controller is dismissed on iOS?

I have two view controllers in a navigation controller, we can navigate from the first view controller to the second view controller.

The audio play code is in the second view controller's viewDidLoad method like this:

let url = NSBundle.mainBundle().URLForResource("audioName", withExtension: "mp3")
        //player = AVAudioPlayer(contentsOfURL: url!)
        do {
            player = try AVAudioPlayer(contentsOfURL: url!)
            //player.play()
            dispatch_async(dispatch_get_main_queue(), {
                self.player.play()
            })
        } catch {
            print("play error")
        }

My question is, when the second view controller is loaded, the audio is playing, but when I dismiss the second view controller and go back to the first view controller, the audio stops playing.

I tried both the play() method directly and the dispatch_async(dispatch_get_main_queue()) method, but the audio just can't continue playing when the second view controller is dismissed.

And also, the audio can automatically play in background on Xcode simulator, I wonder if there is any way to customize this.

The 'player-AVAudioPlayer' is declared in viewcontroller 2. Hence, when viewcontroller 2 is popped, it is released along with the viewcontroller.

Create your 'player-AVAudioPlayer' object as a singleton object and store it in your AppDelegate/ session data. Now for wherever you need to play your audio, just access this object from there and play it. In this way, it will continue playing even after viewcontroller 2 is popped.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM