Play Video in Background using Avplayer

12,492

Solution 1

With surprise I can say that this can be achieved and I just did it.

This method supports all the possibilities:

  • Screen locked by the user;
  • Home button pressed;
  • Switch to other application.

As long as you have an instance of AVPlayer running iOS prevents auto lock of the device.

First you need to configure the application to support audio background from the Info.plist file adding in the UIBackgroundModes array the audio element.

Then put in your AppDelegate.m into - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions:

these methods

[[AVAudioSession sharedInstance] setDelegate: self];    
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];

and #import <AVFoundation/AVFoundation.h>

Then in your view controller that controls AVPlayer

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];
}

and

- (void)viewWillDisappear:(BOOL)animated
{
    [mPlayer pause];    
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
    [self resignFirstResponder];
}

then respond to the

- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
    switch (event.subtype) {
        case UIEventSubtypeRemoteControlTogglePlayPause:
            if([mPlayer rate] == 0){
                [mPlayer play];
            } else {
                [mPlayer pause];
            }
            break;
        case UIEventSubtypeRemoteControlPlay:
            [mPlayer play];
            break;
        case UIEventSubtypeRemoteControlPause:
            [mPlayer pause];
            break;
        default:
            break;
    }
}

Another trick is needed to resume the reproduction if the user presses the home button (in which case the reproduction is suspended with a fade out).

When you control the reproduction of the video (I have play: and pause: methods) set

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];

and

[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];

and the corresponding method to be invoked that will launch a timer and resume the reproduction.

- (void)applicationDidEnterBackground:(NSNotification *)notification
{
    [mPlayer performSelector:@selector(play) withObject:nil afterDelay:0.01];
}

Solution 2

Try this code in your applicationDidEnterBackground:

UIApplication *app = [UIApplication sharedApplication]; 
bgTask = 0;

backgroundTimer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(backgroundTask) userInfo:nil repeats:YES];

bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ 
[app endBackgroundTask:bgTask];

i found it somewhere on the stack works for me

Also check out this tutorial which covers background modes including background audio.. http://www.raywenderlich.com/29948/backgrounding-for-ios

Share:
12,492
S S
Author by

S S

Updated on June 04, 2022

Comments

  • S S
    S S over 1 year

    In my iPhone application I want to keep play video when application enter in background mode.

    I am using AVPlayer and not finding any way to play video in background. I will be very grateful if any one can help me in this. Thanks

  • S S
    S S over 10 years
    mits: Thanks for reply. I have checked link given by you stackoverflow.com/questions/10478622/…, but after reading comments it looks that video will not work in background.
  • S S
    S S over 10 years
    ok thanks, let me check this and I will let you know if it works or not
  • chings228
    chings228 over 10 years
    actually youtube app can play video (through air play ) at background mode. it's awesome
  • Nerrolken
    Nerrolken over 10 years
    Thanks for the code! I've got it all setup in my project and it works with the Home button and switching to another application, but the lockscreen stops the video. However, I've discovered that when I comment out the AVPlayerLayer section, it DOES play on the lockscreen. I obviously need the PlayerLayer, though, to actually see the video. Any idea how to get AVPlayerLayer to just go with the flow that AVPlayer seems fine with, and not stop playing upon locking the phone?
  • user2734823
    user2734823 over 9 years
    @AlexanderWinn this is a bit late, but AVPlayerLayer is NOT supposed to go with the flow lol. Look at apple documentation here: developer.apple.com/library/ios/qa/qa1668/_index.html specifically, "If the AVPlayer's current item is displaying video on the device's display, playback of the AVPlayer is automatically paused when the app is sent to the background. There are two ways to prevent this pause: [...]"
  • Anconia
    Anconia over 8 years
    This was a big help! Please note that in iOS 8 you will not need to set the delegate, as it is deprecated
  • gutenbergn
    gutenbergn over 6 years
    Seems like this isn't working on iOS 11 anymore. Does anyone have any ideas?