9

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
  • 193
  • 1
  • 1
  • 11

6 Answers6

19

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];
}
MacTeo
  • 2,656
  • 1
  • 20
  • 23
  • ok thanks, let me check this and I will let you know if it works or not – S S Mar 21 '13 at 06:06
  • actually youtube app can play video (through air play ) at background mode. it's awesome – chings228 May 06 '13 at 09:30
  • 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? – Nerrolken Aug 13 '13 at 18:53
  • 1
    @AlexanderWinn this is a bit late, but AVPlayerLayer is NOT supposed to go with the flow lol. Look at apple documentation here: https://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: [...]" – user2734823 Aug 10 '14 at 01:09
  • This was a big help! Please note that in iOS 8 you will not need to set the delegate, as it is deprecated – Anconia Jul 26 '15 at 17:23
  • Seems like this isn't working on iOS 11 anymore. Does anyone have any ideas? – gutenbergn Aug 30 '17 at 14:32
1

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

Liftoff
  • 24,717
  • 13
  • 66
  • 119
Obj-Swift
  • 2,802
  • 3
  • 29
  • 50
0

You can do this background task when application is in background :

1> audio
2> location
3> voip
4> newsstand-content
5> external-accessory
6> bluetooth-central
7> bluetooth-peripheral
see this link,

http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html
http://www.rideitdown.com/2012/10/how-to-listen-youtube-videos-in.html

also this may help you: AVPlayer play video in background

Community
  • 1
  • 1
Banker Mittal
  • 1,918
  • 14
  • 26
  • mits: Thanks for reply. I have checked link given by you http://stackoverflow.com/questions/10478622/avplayer-play-video-in-background, but after reading comments it looks that video will not work in background. – S S Mar 18 '13 at 10:12
0

The above answers pause the video for a second when the app enters background, but by using the method mentioned below it keeps the video playing while app goes to background without any glitch.

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:

  1. Disable the video tracks in the player item (file-based content only).
  2. Remove the AVPlayerLayer from its associated AVPlayer (set the AVPlayerLayer player property to nil).

REFERENCE

Playing media while in the background using AV Foundation on iOS

Community
  • 1
  • 1
Vinay Kumar
  • 3,257
  • 1
  • 20
  • 19
0

You can achive your requirement by using below sets of below code.

Swift: 4.2

Just, Create subclass of UIViewController

import UIKit
import AVFoundation

class VideoPlayer:UIViewController{
    var avPlayer: AVPlayer!
    var avPlayerLayer: AVPlayerLayer!
    var paused: Bool = false

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        view.backgroundColor = .clear
        avPlayer?.play()
        paused = false
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let theURL = Bundle.main.url(forResource:"VIDEO_NAME", withExtension: "VIDEO_TYPE") //VIDEO_TYPE -> MP4

        avPlayer = AVPlayer(url: theURL!)
        avPlayerLayer = AVPlayerLayer(player: avPlayer)
        avPlayerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
        avPlayer.volume = 0
        avPlayer.actionAtItemEnd = .none

        avPlayerLayer.frame = view.layer.bounds
        view.backgroundColor = .clear
        view.layer.insertSublayer(avPlayerLayer, at: 0)

        addPlayerNotifications()
    }

    deinit {
        removePlayerNotifations()
    }

    func addPlayerNotifications() {
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(playerItemDidReachEnd(notification:)),
                                               name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
                                               object: avPlayer.currentItem)
        NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
    }

    func removePlayerNotifations() {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
        NotificationCenter.default.removeObserver(self, name:UIApplication.willEnterForegroundNotification, object: nil)
        NotificationCenter.default.removeObserver(self, name:UIApplication.didEnterBackgroundNotification, object: nil)
    }

    @objc func playerItemDidReachEnd(notification: Notification) {
        let p: AVPlayerItem = notification.object as! AVPlayerItem
        p.seek(to: CMTime.zero)
    }


    //App enter in forground.
    @objc func applicationWillEnterForeground(_ notification: Notification) {
        paused = false
        avPlayer?.play()
    }

    //App enter in forground.
    @objc func applicationDidEnterBackground(_ notification: Notification) {
        paused = true
        avPlayer?.pause()
    }

    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        avPlayer.pause()
        paused = true
    }
}

Now, Almoast done. Just create UIViewcontroller class by using sub-class as below.

class Classname: VideoPlayer{
   override func viewDidLoad() {
        super.viewDidLoad()
    }
}
Hitesh Surani
  • 12,733
  • 6
  • 54
  • 65
0

Set AVAudioSession category to .playback mode in viewDidLoad

let audioSession = AVAudioSession.sharedInstance()
do {
     try audioSession.setCategory(.playback, mode: .moviePlayback, options: [])
} catch {
     print("Failed to set audio session category.")
}

Add NotificationObservers

NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)

//App enter in forground.
@objc func applicationWillEnterForeground(_ notification: Notification) {
    // Reconnect the AVPlayer to the presentation when returning to the foreground

    // If presenting video with AVPlayerViewController
    playerViewController.player = player

    // If presenting video with AVPlayerLayer
    playerLayer.player = player
}

//App enter in foreground.
@objc func applicationDidEnterBackground(_ notification: Notification) {
    // Disconnect the AVPlayer from the presentation when entering background

    // If presenting video with AVPlayerViewController
    playerViewController.player = nil

    // If presenting video with AVPlayerLayer
    playerLayer.player = nil
}

References

Playing Audio from a Video Asset in the Background,

AVAudioSession

Sreekuttan
  • 1,579
  • 13
  • 19