有没有可能在后台使用Avplayer播放视频?

时间:2023-01-23 23:01:40

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?

我正在使用Avplayer显示视频剪辑,当我返回(后台应用)时,视频停止。我怎么能继续播放这个视频?

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

我有后台任务和后台线程搜索,IOS只支持后台音乐(不是视频)http://developer.apple.com/library/ios/#文档/iphone/concept /iphoneosprogrammingguide/ManagingYourApplicationsFlow/ managingapplicationsflow.html

here is some discussion about play video in background

下面是一些关于在后台播放视频的讨论

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

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

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

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

但是在AppStore中有很多应用,它们在后台播放视频

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

斯威夫特的球员: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

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

8 个解决方案

#1


12  

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.

只要有一个运行iOS的AVPlayer实例,就可以防止设备的自动锁定。

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

首先,您需要配置应用程序以支持来自Info的音频背景。在uibackgroundmode中添加音频元素的plist文件。

Then put in your AppDelegate.m into

然后输入AppDelegate。米到

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions:

- (BOOL)应用程序:(UIApplication *)应用程序didFinishLaunchingWithOptions:(NSDictionary *)启动选项:

these methods

这些方法

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

and #import < AVFoundation/AVFoundation.h >

和# < AVFoundation / AVFoundation进口。h >

Then in your view controller that controls AVPlayer

然后在控制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).

如果用户按下home按钮,则需要使用另一个技巧来恢复复制(在这种情况下,复制以淡入方式暂停)。

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.

在Backgorund里播放视频对我来说很合适。感谢所有。

#2


3  

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

如果您试图更改后台模式:对不起,应用程序商店不会批准它。MPMoviePlayerViewController回放视频后,为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

在我的研究中,当音轨进入背景时,会有人把它带出来在背景中播放,因为当视频进入前景时,会暂停并获得恢复播放的回放时间

#3


2  

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

使用Avplayer播放背景音乐/视频是不可能的。但这是有可能的

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

MPMoviePlayerViewController。我在我的一个应用中使用了这个播放器和这个应用

is run successfully to appstore.

在appstore中成功运行。

#4


2  

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
  • 在APPNAME-Info中添加uibackgroundmode。plist,选择应用播放音频
  • Then add the AudioToolBox framework to the folder frameworks.
  • 然后将AudioToolBox框架添加到文件夹框架中。
  • In the APPNAMEAppDelegate.h add:

    APPNAMEAppDelegate。h添加:

    -- #import < AVFoundation/AVFoundation.h>

    ——#进口< AVFoundation / AVFoundation.h >

    -- #import < AudioToolbox/AudioToolbox.h>

    ——#进口< AudioToolbox / AudioToolbox.h >

  • In the APPNAMEAppDelegate.m add the following:

    APPNAMEAppDelegate。m添加以下:

    // Set AudioSession

    / /设置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
  • / / 1。覆盖输出音频路径

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

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

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

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

// 2. Changing the default output audio route

/ / 2。更改默认输出音频路径

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];

    (自我。窗口addSubview viewController.view):;

    [self.window makeKeyAndVisible];

    (自我。窗口makeKeyAndVisible];

Enjoy Programming!!

享受编程! !

#5


1  

In addition to fattomhk's response, here's what you can do to achieve video forwarding to the time it should be after your application comes in foreground:

除了fattomhk的回应,以下是你可以做什么来实现视频转发到你的应用程序出现后的时间:

  • Get currentPlaybackTime of playing video when go to background and store it in lastPlayBackTime
  • 获取播放视频的当前回放时间,并将其存储在最后一次回放中
  • Store the time when application goes to background (in userDefault probably)
  • 存储应用程序进入后台的时间(可能在userDefault中)
  • Again get the time when application comes in foreground
  • 再次获得应用程序出现在前台的时间
  • Calculate the duration between background and foreground time
  • 计算背景和前景时间之间的持续时间
  • Set current playback time of video to lastPlayBackTime + duration
  • 设置当前视频回放时间为最新回放时间+持续时间

#6


1  

Swift version for the accepted answer.

接受答案的Swift版本。

In the delegate:

在委托:

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

In the view controller that controls AVPlayer

在控制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"

不要忘记“导入AVFoundation”

#7


0  

If you are Playing video using WebView you can handle using javascript to play video on background.

如果您正在使用WebView播放视频,您可以使用javascript在后台播放视频。

strVideoHTML = @"<html><head><style>body.........</style></head> <body><div id=\"overlay\"><div id=\"youtubelogo1\"></div></div><div id=\"player\"></div> <script> var tag = document.createElement('script'); tag.src = \"http://www.youtube.com/player_api\"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; events: { 'onReady': onPlayerReady, } }); } function onPlayerReady(event) { event.target.playVideo(); } function changeBG(url){ document.getElementById('overlay').style.backgroundImage=url;} function manualPlay() {  player.playVideo(); }  function manualPause() {  player.pauseVideo(); }  </script></body> </html>";

NSString *html = [NSString stringWithFormat:strVideoHTML,url, width, height,videoid;
webvideoView.delegate = self;
[webvideoView loadHTMLString:html baseURL:[NSURL URLWithString:@"http://www.your-url.com"]];

On view diappear call

在视图diappear调用

strscript = @"manualPlay();
[webvideoView stringByEvaluatingJavaScriptFromString:strscript];

#8


0  

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.

我想补充一些东西,出于某种原因,最终成为我的罪魁祸首。我使用AVPlayer和背景播放已经有很长一段时间了,没有任何问题,但这次我就是无法让它发挥作用。

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.

我发现当你进入后台时,AVPlayer的rate属性有时会降到0.0(即暂停),因此我们只需要KVO始终检查rate属性,或者至少当我们进入后台时。如果速率低于0.0,我们可以假设用户想玩(即用户没有故意在遥控器上点击暂停,电影结束,等等)我们需要调用。play()在AVPlayer上。

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

在AVPlayer上没有其他选项可以让它在应用进入后台时不停顿。

#1


12  

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.

只要有一个运行iOS的AVPlayer实例,就可以防止设备的自动锁定。

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

首先,您需要配置应用程序以支持来自Info的音频背景。在uibackgroundmode中添加音频元素的plist文件。

Then put in your AppDelegate.m into

然后输入AppDelegate。米到

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions:

- (BOOL)应用程序:(UIApplication *)应用程序didFinishLaunchingWithOptions:(NSDictionary *)启动选项:

these methods

这些方法

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

and #import < AVFoundation/AVFoundation.h >

和# < AVFoundation / AVFoundation进口。h >

Then in your view controller that controls AVPlayer

然后在控制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).

如果用户按下home按钮,则需要使用另一个技巧来恢复复制(在这种情况下,复制以淡入方式暂停)。

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.

在Backgorund里播放视频对我来说很合适。感谢所有。

#2


3  

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

如果您试图更改后台模式:对不起,应用程序商店不会批准它。MPMoviePlayerViewController回放视频后,为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

在我的研究中,当音轨进入背景时,会有人把它带出来在背景中播放,因为当视频进入前景时,会暂停并获得恢复播放的回放时间

#3


2  

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

使用Avplayer播放背景音乐/视频是不可能的。但这是有可能的

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

MPMoviePlayerViewController。我在我的一个应用中使用了这个播放器和这个应用

is run successfully to appstore.

在appstore中成功运行。

#4


2  

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
  • 在APPNAME-Info中添加uibackgroundmode。plist,选择应用播放音频
  • Then add the AudioToolBox framework to the folder frameworks.
  • 然后将AudioToolBox框架添加到文件夹框架中。
  • In the APPNAMEAppDelegate.h add:

    APPNAMEAppDelegate。h添加:

    -- #import < AVFoundation/AVFoundation.h>

    ——#进口< AVFoundation / AVFoundation.h >

    -- #import < AudioToolbox/AudioToolbox.h>

    ——#进口< AudioToolbox / AudioToolbox.h >

  • In the APPNAMEAppDelegate.m add the following:

    APPNAMEAppDelegate。m添加以下:

    // Set AudioSession

    / /设置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
  • / / 1。覆盖输出音频路径

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

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

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

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

// 2. Changing the default output audio route

/ / 2。更改默认输出音频路径

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];

    (自我。窗口addSubview viewController.view):;

    [self.window makeKeyAndVisible];

    (自我。窗口makeKeyAndVisible];

Enjoy Programming!!

享受编程! !

#5


1  

In addition to fattomhk's response, here's what you can do to achieve video forwarding to the time it should be after your application comes in foreground:

除了fattomhk的回应,以下是你可以做什么来实现视频转发到你的应用程序出现后的时间:

  • Get currentPlaybackTime of playing video when go to background and store it in lastPlayBackTime
  • 获取播放视频的当前回放时间,并将其存储在最后一次回放中
  • Store the time when application goes to background (in userDefault probably)
  • 存储应用程序进入后台的时间(可能在userDefault中)
  • Again get the time when application comes in foreground
  • 再次获得应用程序出现在前台的时间
  • Calculate the duration between background and foreground time
  • 计算背景和前景时间之间的持续时间
  • Set current playback time of video to lastPlayBackTime + duration
  • 设置当前视频回放时间为最新回放时间+持续时间

#6


1  

Swift version for the accepted answer.

接受答案的Swift版本。

In the delegate:

在委托:

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

In the view controller that controls AVPlayer

在控制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"

不要忘记“导入AVFoundation”

#7


0  

If you are Playing video using WebView you can handle using javascript to play video on background.

如果您正在使用WebView播放视频,您可以使用javascript在后台播放视频。

strVideoHTML = @"<html><head><style>body.........</style></head> <body><div id=\"overlay\"><div id=\"youtubelogo1\"></div></div><div id=\"player\"></div> <script> var tag = document.createElement('script'); tag.src = \"http://www.youtube.com/player_api\"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; events: { 'onReady': onPlayerReady, } }); } function onPlayerReady(event) { event.target.playVideo(); } function changeBG(url){ document.getElementById('overlay').style.backgroundImage=url;} function manualPlay() {  player.playVideo(); }  function manualPause() {  player.pauseVideo(); }  </script></body> </html>";

NSString *html = [NSString stringWithFormat:strVideoHTML,url, width, height,videoid;
webvideoView.delegate = self;
[webvideoView loadHTMLString:html baseURL:[NSURL URLWithString:@"http://www.your-url.com"]];

On view diappear call

在视图diappear调用

strscript = @"manualPlay();
[webvideoView stringByEvaluatingJavaScriptFromString:strscript];

#8


0  

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.

我想补充一些东西,出于某种原因,最终成为我的罪魁祸首。我使用AVPlayer和背景播放已经有很长一段时间了,没有任何问题,但这次我就是无法让它发挥作用。

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.

我发现当你进入后台时,AVPlayer的rate属性有时会降到0.0(即暂停),因此我们只需要KVO始终检查rate属性,或者至少当我们进入后台时。如果速率低于0.0,我们可以假设用户想玩(即用户没有故意在遥控器上点击暂停,电影结束,等等)我们需要调用。play()在AVPlayer上。

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

在AVPlayer上没有其他选项可以让它在应用进入后台时不停顿。