简体   繁体   English

如何在后台模式下继续播放音频

[英]How to continue audio playback in background mode

I have a UIWebView that plays video clips in my view controller. 我有一个UIWebView,可以在我的视图控制器中播放视频片段。 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. 为此,我在AppDelegate.swift中使用以下代码。

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? 如何启用MPMusicPlayerController / AVAudioPlayer(我真的不确定它是什么)继续播放,这样用户就不必手动按播放了?

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". 我还在目标设置中的背景模式下选中了“音频和Airplay”,并将所需背景模式设置为“App播放音频或使用AirPlay传输音频/视频”。

var error: NSError?
var success = AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: &error)
if !success {
     NSLog("Failed to set audio session category.  Error: \(error)")
}

UPDATE: I'm creating a custom view in my appDel to accommodate a video mini player. 更新:我正在我的appDel创建一个自定义视图,以容纳视频迷你播放器。 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. CustomWindowUIWindow的自定义类,我在其中添加一个迷你播放器到视图层次结构的顶部。 In this code, am I calling that method before creating the UIWebView ? 在这段代码中,我在创建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)")
}

Important: 重要:

  1. Don't use simulator for tests. 不要使用模拟器进行测试。 Background playback doesn't work in the Simulator; 后台播放在模拟器中不起作用;
  2. Call above code before creating UIWebView instance. 在创建UIWebView实例之前调用上面的代码。

Sources: 1 , 2 . 资料来源: 12

You can play music in lockscreen with 你可以用锁屏播放音乐

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)")
}

After it You Need to add Background Modes in the capabilities Like this. 之后你需要在功能中添加背景模式像这样。 And don't test this on simulator It does not work on simulator. 并且不要在模拟器上测试它在模拟器上不起作用。 Hope it helps 希望能帮助到你 在此输入图像描述

and this is how you can handal previous,next,pause and play :- 这就是你如何处理前一个,下一个,暂停和玩游戏: -

- (void) remoteControlReceivedWithEvent: (UIEvent *) receivedEvent

 {

    if (receivedEvent.type == UIEventTypeRemoteControl) 
{
        switch (receivedEvent.subtype)
 {
            case UIEventSubtypeRemoteControlTogglePlayPause:
                [self togglePlayPause];
                break;
            case UIEventSubtypeRemoteControlPreviousTrack:
                [self playPrevTrack];
                break;
            case UIEventSubtypeRemoteControlNextTrack:
                [self playNextTrack];
                break;
            default:
                break;
        }
    }
}

In swift you can use it Like that 在swift中你可以像那样使用它

override func remoteControlReceivedWithEvent(event: UIEvent) {
        let rc = event.subtype

        println("received remote control \(rc.rawValue)") // 101 = pause, 100 = play
        switch rc {
        case .RemoteControlTogglePlayPause:

            self.togglePlayPause()
        break;
        case .RemoteControlPreviousTrack:
            self.playPrevTrack()
         break;
        case .RemoteControlNextTrack:
            self.playNextTrack()
        break;
        default:break
        }

A common "trick" is to play a white sound that keeps your app running. 一个常见的“技巧”是播放白色声音,让您的应用程序保持运行。 But it will display a red bold status bar 但它会显示一个红色的粗体状态栏

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

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