2013-01-24 80 views
4

我看到一张纸条,上面这个地址 http://developer.apple.com/library/ios/#qa/qa1668/_index.html视频播放的背景

注:如果您在电影中禁用视频轨道,或将其从相关AVPlayer卸下AVPlayerLayer它将使电影音频继续在后台播放。但是,这些更改必须在应用程序切换到后台之前生效。

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

该程序的工作原理。但在背景中,声音被切断。我想继续播放背景音效。我如何从AVPlayer中分离AVPlayerLayer?

回答

1

上面你的代码是好的,但是从背景转换到/在做这些事情:

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

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

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

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

干杯。

+0

我认为这可能正是我所需要的!但是,快速的问题(可能是noobish):'applicationWillResignActive'是一个'AppDelegate'方法,我所有的'AVPlayerLayer'代码都在一个单独的ViewController文件中。能够在AppDelegate中引用VideoViewController的播放器的最佳方式是什么?将VideoVideoController导入到AppDelegate中,还是在应用程序范围内“获取AVPlayer当前正在运行的”方法或其他东西?那里的最佳做法是什么? – Nerrolken

+0

您可以使用委托或通知。 (1)对于代表的使用,请参阅此stackoverflow问题:http://stackoverflow.com/questions/626898/how-do-i-create-delegates-in-objective-c。 (2)有关通知,请参阅:http://stackoverflow.com/questions/9011868/whats-the-best-way-to-detect-when-the-app-is-entering-the-background-for-我的看法。我会建议使用通知。 (使用UIApplicationDidBecomeActiveNotification和UIApplicationWillResignActiveNotification)。 – mltpyt