Is it possible to play video using Avplayer in Bac

2019-01-13 11:39发布

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 & background thread ,IOS only support music in background (Not video) http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html

here is some discussion about play video in background

1) https://discussions.apple.com/thread/2799090?start=0&tstart=0

2) http://www.cocoawithlove.com/2011/04/background-audio-through-ios-movie.html

But there are many apps in AppStore, that play video in Background like

Swift Player : https://itunes.apple.com/us/app/swift-player-speed-up-video/id545216639?mt=8&ign-mpt=uo%3D2

SpeedUpTV : https://itunes.apple.com/ua/app/speeduptv/id386986953?mt=8

8条回答
三岁会撩人
2楼-- · 2019-01-13 11:45

This method supports all the possibilities:

  • Screen locked by the user;
  • List item
  • Home button pressed;

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 methods) set

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground:) 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];
}

Its works for me to play video in Backgorund. Thanks to all.

查看更多
冷血范
3楼-- · 2019-01-13 11:45

If you try to change the background mode: Sorry, App store wont approve it.MPMoviePlayerViewController playback video after going to background for youtube

In my research, someone would take the sound track out to play in te background when it goes into background as the video would be pause and get the playbacktime for resume playing when go into foreground

查看更多
Viruses.
4楼-- · 2019-01-13 11: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!!

查看更多
三岁会撩人
5楼-- · 2019-01-13 11:49

It is not possible to play background music/video using Avplayer. But it is possible using

MPMoviePlayerViewController. I have done this in one of my app using this player & this app

is run successfully to appstore.

查看更多
够拽才男人
6楼-- · 2019-01-13 11:50

I'd like to add something that for some reason ended up being the culprit for me. I had used AVPlayer and background play for a long time without problems, but this one time I just couldn't get it to work.

I found out that when you go background, the rate property of the AVPlayer sometimes seems to dip to 0.0 (i.e. paused), and for that reason we simply need to KVO check the rate property at all times, or at least when we go to background. If the rate dips below 0.0 and we can assume that the user wants to play (i.e. the user did not deliberately tap pause in remote controls, the movie ended, etc) we need to call .play() on the AVPlayer again.

AFAIK there is no other toggle on the AVPlayer to keep it from pausing itself when app goes to background.

查看更多
爷、活的狠高调
7楼-- · 2019-01-13 11:52

Swift version for the accepted answer.

In the delegate:

AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)

In the view controller that controls AVPlayer

override func viewDidAppear(animated: Bool) {
    UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
    self.becomeFirstResponder()
}

override func viewWillDisappear(animated: Bool) {
    mPlayer.pause()
    UIApplication.sharedApplication().endReceivingRemoteControlEvents()
    self.resignFirstResponder()
}

Don't forget to "import AVFoundation"

查看更多
登录 后发表回答