我有一个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)") }重要提示:
来源: 1 , 2 。
更多推荐
如何在后台模式下继续播放音频
发布评论