如何在后台模式下继续播放音频 [英] How to continue audio playback in background mode
问题描述
我有一个UIWebView,可以在我的视图控制器中播放视频片段。当我退出应用程序时,音频将停止播放,尽管我可以在控制中心按播放以再次继续播放。要做到这一点,我在我的AppDelegate.swift中使用以下代码。
I have a UIWebView that plays video clips in my view controller. When I exit the app, the audio will stop playing, although I can press play in the control center to continue it again. To do that I'm using the following code in my AppDelegate.swift.
当应用程序进入后台时,我希望音频自动开始播放。如何启用MPMusicPlayerController / AVAudioPlayer(我真的不确定它是什么)继续播放,这样用户就不必手动按播放了?
When the app enters the background, I'd like the audio to start playing automatically. How can I enable the MPMusicPlayerController/AVAudioPlayer (I'm really not sure which it is) to continue playing so the user doesn't have to manually press play?
I还在我的目标设置中的背景模式下选中音频和Airplay,并将所需背景模式设置为App播放音频或使用AirPlay播放音频/视频。
I also have "Audio and Airplay" checked under Background Modes in my target settings, and Required Background Modes set to "App plays audio or streams audio/video using AirPlay".
var error: NSError?
var success = AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: &error)
if !success {
NSLog("Failed to set audio session category. Error: \(error)")
}
更新:我正在 appDel
中创建自定义视图以容纳视频迷你播放器。这就是我创造它的方式。 CustomWindow
是一个自定义类 UIWindow
我在这里添加一个迷你播放器到视图层次结构的顶部。在这段代码中,我在创建 UIWebView
之前调用该方法吗?
UPDATE: I'm creating a custom view in my appDel
to accommodate a video mini player. Here's how I'm creating it. CustomWindow
is a custom class of UIWindow
where I'm adding a mini player to the top of the view hierarchy. In this code, am I calling that method before creating the UIWebView
?
class AppDelegate: UIResponder, UIApplicationDelegate {
let myWind = CustomWindow(frame:UIScreen.mainScreen().bounds)
var window: UIWindow? {
set {
}
get {
return myWind
}
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
var error: NSError?
var success = AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: &error)
if success {
AVAudioSession.sharedInstance().setActive(true, error: nil)
UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
} else {
NSLog("Failed to set audio session category. Error: \(error)")
}
myWind.showOrHidePopupWindow()
}
推荐答案
尝试使用以下代码更新代码:
Try to update you code with this:
var error: NSError?
var success = AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: &error)
if success {
AVAudioSession.sharedInstance().setActive(true, error: nil)
UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
} else {
NSLog("Failed to set audio session category. Error: \(error)")
}
重要提示:
- 不要使用模拟器进行测试。后台播放在模拟器中不起作用;
- 在创建
UIWebView
实例之前调用上面的代码。
- Don't use simulator for tests. Background playback doesn't work in the Simulator;
- Call above code before creating
UIWebView
instance.
这篇关于如何在后台模式下继续播放音频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!