【问题标题】:Video Playback in the Background在后台播放视频
【发布时间】:2013-01-24 13:32:39
【问题描述】:

我看到一个注释,这个地址 http://developer.apple.com/library/ios/#qa/qa1668/_index.html

注意:如果您禁用电影中的视频轨道,或将 AVPlayerLayer 从其关联的 AVPlayer 中分离出来,它将允许电影音频继续在后台播放。但是,这些更改必须在应用程序实际切换到后台之前生效。

   [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
   [self becomeFirstResponder];

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



    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:[NSURL fileURLWithPath:AnUrl]];
   AVPlayer *avPlayer = [AVPlayer playerWithPlayerItem:playerItem];


   AVPlayerLayer *avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:avPlayer];
   avPlayerLayer.frame = self.view.layer.bounds;
   UIView *newView = [[UIView alloc] initWithFrame:self.view.bounds];
   [newView.layer addSublayer:avPlayerLayer];
   [self.view addSubview:newView];

   [avPlayer play];

这个程序有效。但是在后台,声音被切断了。我想继续播放只有背景的声音。如何将 AVPlayerLayer 与 AVPlayer 分离?

【问题讨论】:

    标签: iphone ios objective-c avplayer avplayerlayer


    【解决方案1】:

    上面的代码没问题,但是在转换到/从后台时做这些事情:

    • 当应用程序激活时:(您的 avPlayerLayer 必须是您添加到视图中的 AVPlayerLayer)

      - (void)applicationDidBecomeActive:(UIApplication *)application {
          [avPlayerLayer playerLayerWithPlayer:avPlayer];
      
      }
      
    • 当应用程序进入后台时:(您的 avPlayerLayer 必须是您添加到视图中的 AVPlayerLayer)

      - (void)applicationWillResignActive:(UIApplication *)application {
          [avPlayerLayer playerLayerWithPlayer:nil];
      }
      

    另外,不要忘记在 plist 的 UIBackgroundModes 中添加音频。

    干杯。

    【讨论】:

    • 我想这可能正是我所需要的!快速的问题(可能是noobish):applicationWillResignActive 是一个AppDelegate 方法,我所有的AVPlayerLayer 代码都在一个单独的ViewController 文件中。能够在 AppDelegate 中引用 VideoViewController 的播放器的最佳方式是什么?将 VideoVideoController 导入 AppDelegate,或者是否有一个应用程序范围的“获取当前正在运行的 AVPlayer”方法或什么?那里的最佳做法是什么?
    • 您可以使用委托或通知。 (1) 关于委托的使用,请参见这个 stackoverflow 问题:stackoverflow.com/questions/626898/…。 (2) 通知请见:stackoverflow.com/questions/9011868/…。我建议使用通知。 (使用 UIApplicationDidBecomeActiveNotification 和 UIApplicationWillResignActiveNotification)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-13
    • 1970-01-01
    • 2015-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-27
    相关资源
    最近更新 更多