Play video in background

I noticed that this address is http://developer.apple.com/library/ios/#qa/qa1668/_index.html

Note. If you turn off the video tracks in the movie or disconnect AVPlayerLayer from the associated AVPlayer, this will allow the video sound to continue playing in the background. However, these changes must be valid before the application really switches to the background.

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

This program works. But in the background, the sound is muted. I want to continue playing only sound. How do I disconnect between AVPlayerLayer from AVPlayer?

+4
source share
1 answer

Your code above is fine, but do this while going to / from the background:

  • When the application becomes active: (Your avPlayerLayer must be added to your AVPlayerLayer)

     - (void)applicationDidBecomeActive:(UIApplication *)application { [avPlayerLayer playerLayerWithPlayer:avPlayer]; } 
  • When the application goes into the background: (Your avPlayerLayer should be the AVPlayerLayer that you added to your view)

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

Also, be sure to add audio to your plist's UIBackgroundModes.

Greetings.

+1
source

All Articles