Is it possible to play video using Avplayer in Background?

前端 未结 8 1367
清歌不尽
清歌不尽 2020-12-04 20:19

I am using Avplayer to show video clips and when i go back (app in background) video stop. How can i keep playing the video?

I have search about background task &am

8条回答
  •  庸人自扰
    2020-12-04 20:47

    Try with this snippet, I've already integrated this with my app & it's being useful for me..hope this will work for you!!

    Follow the steps given below:

    • Add UIBackgroundModes in the APPNAME-Info.plist, with the selection App plays audio
    • Then add the AudioToolBox framework to the folder frameworks.
    • In the APPNAMEAppDelegate.h add:

      -- #import < AVFoundation/AVFoundation.h>

      -- #import < AudioToolbox/AudioToolbox.h>

    • In the APPNAMEAppDelegate.m add the following:

      // Set AudioSession

       NSError *sessionError = nil;
      
          [[AVAudioSession sharedInstance] setDelegate:self];
      
          [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
      
    • /* Pick any one of them */

    • // 1. Overriding the output audio route

    //UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker; //AudioSessionSetProperty(kAudioSessionProperty_OverrideAudioRoute, sizeof(audioRouteOverride), &audioRouteOverride);

    ========================================================================

    // 2. Changing the default output audio route

    UInt32 doChangeDefaultRoute = 1;
    
    AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryDefaultToSpeaker, sizeof(doChangeDefaultRoute), &doChangeDefaultRoute);
    

    into the

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    • but before the two lines:

      [self.window addSubview:viewController.view];

      [self.window makeKeyAndVisible];

    Enjoy Programming!!

提交回复
热议问题