简体   繁体   English

在iOS上关闭View Controller后,如何继续播放音频?

[英]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: 音频播放代码在第二个视图控制器的viewDidLoad方法中,如下所示:

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. 我直接尝试了play()方法和dispatch_async(dispatch_get_main_queue())方法,但是当关闭第二个视图控制器时,音频只是无法继续播放。

And also, the audio can automatically play in background on Xcode simulator, I wonder if there is any way to customize this. 而且,音频可以在Xcode模拟器上自动在后台播放,我想知道是否有任何方法可以对此进行自定义。

The 'player-AVAudioPlayer' is declared in viewcontroller 2. Hence, when viewcontroller 2 is popped, it is released along with the viewcontroller. 在视图控制器2中声明了“ player-AVAudioPlayer”。因此,当弹出视图控制器2时,它会与视图控制器一起释放。

Create your 'player-AVAudioPlayer' object as a singleton object and store it in your AppDelegate/ session data. 将您的“ player-AVAudioPlayer”对象创建为单例对象,并将其存储在AppDelegate /会话数据中。 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. 这样,即使在弹出ViewController 2之后,它也将继续播放。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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