要想在iOS设备上进行后台音频播放的话,首先要在info.plist中设置允许后台播放音频。如下:
AVPlayer后台播放音频的_第1张图片
 
然后还要在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions方法里面设置 AVAudioSession的模式,通常如下设置即可:
UIDevice* device = [UIDevice currentDevice];
    if ([device respondsToSelector:@selector(isMultitaskingSupported)]) {
        if(device.multitaskingSupported) {
            NSLog(@"background supported");
           
            AVAudioSession *audioSession = [AVAudioSession sharedInstance];
            NSError *aError = nil;
            [audioSession setCategory:AVAudioSessionCategoryPlayback error:&aError];
            if(aError){
                NSLog(@"set Category error:%@", [aError description]);
            }
            aError = nil;
            [audioSession setActive:YES error:&aError];
            if(aError){
                NSLog(@"active Category error:%@", [aError description]);
            }
            audioSession.delegate = [MyViewController sharedInstance];//这个在后面会讲到
        }
    }
 
经过上面两步简单的设置后,后台勉强可以播放了(当然是勉强的);
 
但是你有可能发现它有时候在后台播着播着它就无故停止了,其实并不是无故,而是有故的。就是因为app进入后台运行时其实并不是后台运行,只有有限的时间让你处理一些必要的保存等操作,然后app就会被挂起了。
好了,要解决这个问题可以有多种方法:
1.可以在你avplayer的播放可能出现暂停或者停止的时候插入一个 UIBackgroundTaskIdentifier bgTaskId;并在开始播放的时候 [[UIApplication sharedApplication] endBackgroundTask:bgTaskId];
2.当然有更简便的方法,我就是采用这个方法的:
          在appdelegate中声明一个变量:UIBackgroundTaskIdentifier bgTaskId;
          在进入后台运行的的时候:- (void)applicationWillResignActive:(UIApplication *)application
{
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
   
    NSLog(@"-------------------------applicationWillResignActive");
   
    //added by lyh 2012-3-5 , for Try to solve the backward playback
    if ([[MyViewController sharedInstance] isPlaying]) {//这个是我判断是否要播放
        UIDevice* device = [UIDevice currentDevice];
        if ([device respondsToSelector:@selector(isMultitaskingSupported)]) {
            if(device.multitaskingSupported) {
                if (bgTaskId == UIBackgroundTaskInvalid) {
                    bgTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];
                }
            }
        }
    }
}
而在进入前台运行的时候,要把这个任务结束掉,不然就浪费了。呵呵
- (void)applicationDidBecomeActive:(UIApplication *)application
{
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
   
    NSLog(@"-------------------------applicationDidBecomeActive");
   
    //added by lyh 2012-3-5
    if (bgTaskId != UIBackgroundTaskInvalid) {
        [[UIApplication sharedApplication] endBackgroundTask:bgTaskId];
        bgTaskId = UIBackgroundTaskInvalid;
    }
}
上面的方法可以解决有时候后台播放着就停止了的问题。
现在还有个问题,就是要是当前Active的不是MyViewController的时候,此时进入后台播放,是不会播放的,因为audioSession.delegate = [MyViewController sharedInstance];而当前Active的不是MyViewController,所以它就不能播放了,呵呵,我也不知道它为什么不播放。我只知道比较山寨而且简单的解决办法就是,所有ViewController都继承MyViewController这个类即可解决。
  不用這種山寨的辦法,這個問題的解決其實也很簡單,就是在每個viewcontroller實現以下兩個方法:
[cpp]  view plain copy
  1. -(void) viewDidAppear:(BOOL)animated {  
  2.     [super viewDidAppear:animated];  
  3.     
  4.     [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];         
  5.     [self becomeFirstResponder];   
  6. }  
  7.   
  8. -(void)viewDidDisappear:(BOOL)animated  
  9. {  
  10.     [[UIApplication sharedApplication] endReceivingRemoteControlEvents];         
  11.     [self resignFirstResponder];               
  12.     [super viewDidDisappear:animated];  
  13. }  
----------------------------------------------------------------------------------------------------------------------
PS:以上是我在做项目过程中遇到的问题和解决办法,要是哪里错了欢迎指正!