【问题标题】:Is it possible to play video using Avplayer in Background?是否可以在后台使用 Avplayer 播放视频?
【发布时间】:2013-03-06 09:55:13
【问题描述】:

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

我搜索了后台任务和后台线程,IOS只支持背景音乐(不支持视频) http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html

这里有一些关于在后台播放视频的讨论

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

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

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

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

加速电视:https://itunes.apple.com/ua/app/speeduptv/id386986953?mt=8

【问题讨论】:

  • +1 对这个问题的研究!

标签: iphone ios ios5 video avplayer


【解决方案1】:

此方法支持所有可能性:

  • 屏幕被用户锁定;
  • 列表项
  • 按下主页按钮;

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

首先,您需要配置应用程序以支持 Info.plist 文件中的音频背景,并在 UIBackgroundModes 数组中添加音频元素。

然后把你的AppDelegate.m放进去

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

这些方法

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

#import

然后在控制 AVPlayer 的视图控制器中

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

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

然后回复

 - (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;
        }
    }

如果用户按下主页按钮,则需要另一个技巧来恢复再现(在这种情况下,再现会因淡出而暂停)。

当你控制视频的再现时(我有播放方法)设置

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

以及要调用的将启动计时器并恢复复制的相应方法。

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

它适用于我在 Backgorund 中播放视频。 谢谢大家。

【讨论】:

  • 嗨@V.K.,我刚刚设置播放视频音频背景类似于你的指令。但我只在按下主页按钮时播放,如果我打开锁屏。音频将在几秒钟后停止。 :( 我该如何解决这个问题?
  • [[AVAudioSession sharedInstance] setDelegate: self]; [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]; // 在 AppDelegate 中添加这个,
  • 我只是将此代码添加到AppDelegate,但没有解决。在 didFinishLaunchingWithOptions 中,我添加: [[AVAudioSession sharedInstance] setDelegate:self]; [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];我有视图控制器使用 AVPlayer 播放视频。在这个视图控制器中,我添加: [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; [自己成为FirstResponder]; ...获取远程控制事件。后台播放的时候没问题。但是,当 AVPlayer 继续运行时锁定屏幕音频将停止...
  • - (BOOL)canBecomeFirstResponder { return YES; } //.... 在 AvPlayer 屏幕中添加此代码并签入设备
【解决方案2】:

如果您尝试更改后台模式: 抱歉,App store 不会批准的。MPMoviePlayerViewController playback video after going to background for youtube

在我的研究中,有人会在进入后台时将音轨拿出​​来在后台播放,因为视频会暂停并获得播放时间以在进入前台时恢复播放

【讨论】:

  • 有没有其他方法可以在后台播放视频?
  • @Horst 我们能否在 AVPlayer 中拥有像 MPMoviePlayerViewController 这样的功能,当应用程序进入后台时视频会暂停并在前台恢复播放时间??
  • 您可以在这里了解更多信息:developer.apple.com/library/ios/qa/qa1668/_index.html
【解决方案3】:

无法使用 Avplayer 播放背景音乐/视频。但是可以使用

MPMoviePlayerViewController。我已经在我的一个应用中使用此播放器和此应用完成了此操作

成功运行到应用商店。

【讨论】:

  • 不,伙计,这是可能的。看我的答案。它非常适合我。并感谢您的建议。将来我会尝试使用 MPMoviePlayerViewController。
  • @V.K.我们可以在应用程序进入后台时暂停视频,并在应用程序在前台使用 AVPlayer 时恢复视频?可以使用 AVPlayer 吗?
【解决方案4】:

试试这个 sn-p,我已经将它与我的应用程序集成,它对我很有用..希望这对你有用!!

按照下面给出的步骤:

  • 在 APPNAME-Info.plist 中添加 UIBackgroundModes,并选择 应用播放音频
  • 然后将 AudioToolBox 框架添加到文件夹 frameworks 中。
  • 在APPNAMEAppDelegate.h 中添加:

    -- #import < AVFoundation/AVFoundation.h>

    -- #import < AudioToolbox/AudioToolbox.h>

  • 在 APPNAMEAppDelegate.m 中添加以下内容:

    // 设置音频会话

     NSError *sessionError = nil;
    
        [[AVAudioSession sharedInstance] setDelegate:self];
    
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
    
  • /* 选择其中任何一个 */

  • // 1. 覆盖输出音频路由

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

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

// 2. 更改默认输出音频路由

UInt32 doChangeDefaultRoute = 1;

AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryDefaultToSpeaker, sizeof(doChangeDefaultRoute), &doChangeDefaultRoute);

进入

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  • 但在这两行之前:

    [self.window addSubview:viewController.view];

    [self.window makeKeyAndVisible];

享受编程!

【讨论】:

  • 当你控制视频的再现时(我有播放方法)设置 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];以及要调用的相应方法,该方法将启动计时器并恢复再现。 - (void)applicationDidEnterBackground:(NSNotification *)notification { [mPlayer performSelector:@selector(play) withObject:nil afterDelay:0.01]; } 它对我有用
  • 你应该相信这个 sn-p 的原始来源,Patrick Rorth:devforums.apple.com/thread/90684?start=0&tstart=0
【解决方案5】:

已接受答案的 Swift 版本。

在委托中:

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

在控制 AVPlayer 的视图控制器中

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

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

别忘了“导入 AVFoundation”

【讨论】:

  • var mPlayer = AVPlayer()
【解决方案6】:

除了 fattomhk 的响应之外,您还可以执行以下操作来将视频转发到应用程序进入前台后的时间:

  • 去后台获取播放视频的currentPlaybackTime并存入lastPlayBackTime
  • 存储应用程序进入后台的时间(可能在userDefault中)
  • 再次获取应用程序进入前台的时间
  • 计算后台时间和前台时间之间的duration
  • 设置视频当前播放时间为lastPlayBackTime + duration

【讨论】:

  • 在backgorund中,如何播放视频音乐?
  • 从视频中取出音轨。并且玩那个parllely。
  • 缓冲延迟怎么样?
【解决方案7】:

如果您使用 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"]];

查看消失通话

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

【讨论】:

    【解决方案8】:

    我想添加一些由于某种原因最终成为我的罪魁祸首的东西。我用 AVPlayer 和后台播放很长时间都没有问题,但这一次我就是无法正常工作。

    我发现当你进入后台时,AVPlayerrate 属性有时似乎下降到 0.0(即暂停),因此我们只需要随时 KVO 检查 rate 属性,或者至少当我们进入背景时。如果速率下降到 0.0 以下并且我们可以假设用户想要播放(即用户没有故意点击遥控器中的暂停、电影结束等),我们需要再次调用 AVPlayer 上的.play()

    AFAIK 在 AVPlayer 上没有其他开关可以防止它在应用程序进入后台时自行暂停。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-02
      • 1970-01-01
      相关资源
      最近更新 更多