简体   繁体   中英

AVPlayerLayer stop play when enter background mode

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM