3

I setup AVPlayerLayer with :

        audioPlayer = [[AVPlayer alloc]initWithURL:[NSURL fileURLWithPath:fileName]];
        avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:audioPlayer];
        [avPlayerLayer setFrame:self.view.bounds];
        [[self.view layer] addSublayer:avPlayerLayer];
        [audioPlayer play];

In the AppDelegete i add :

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

Now in UIViewController Class i add:

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

- (BOOL)canBecomeFirstResponder {
    return YES;
}

- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
    switch (event.subtype) {
        case UIEventSubtypeRemoteControlTogglePlayPause:
            if (audioPlayer.rate == 0.0) {
                [avPlayerLayer.player play];
            } else {
                [avPlayerLayer.player pause];
            }
            NSLog(@"4");
            break;
        case UIEventSubtypeRemoteControlPlay:
            [avPlayerLayer.player play];
            break;
        case UIEventSubtypeRemoteControlPause:
            [avPlayerLayer.player pause];
            NSLog(@"3");
            break;
        case UIEventSubtypeRemoteControlNextTrack:
            [self didPressNextSong:nil];
            NSLog(@"2");
            break;
        case UIEventSubtypeRemoteControlPreviousTrack:
            [self didPressLastSong:nil];
            NSLog(@"1");
            break;
        default:
            break;
    }
}

Now the problem is that when i move to background mode the song stop playing but when i press the play button in the remote control(the menu that popup when i press double click on the home button) the song keep playing from where it stoped.

Any idea why i have this issue?

YosiFZ
  • 7,792
  • 21
  • 114
  • 221
  • I'm having the same problem as you. Did you ever find a fix? From what I found, the AVPlayer will play background audio as long as there is no AVPlayerLayer associated with it (and as long as everything in Joshua Smith's answer is implemented). However, the app seems to go into the background too quickly for me to nil the AVPlayerLayer in applicationWillResignActive, and my audio gets cut off. If you know a fix, I'd be eternally grateful! – mrabin Jan 09 '13 at 18:50

1 Answers1

0

See this solution:

How do I get my AVPlayer to play while app is in background?

The key is in the UIBackgroundModes in the info plist.

Community
  • 1
  • 1
Joshua Smith
  • 6,561
  • 1
  • 30
  • 28