LarryFisherman
LarryFisherman

Reputation: 322

Playing AVAudio from iPod Library while device is locked

Just a quick question.

I've set up my program to be able to play AVAudioPlayer and AVPlayer in the background, which is working fine. I can play a song, lock my screen and the sound will continue to play.

What I'm having trouble with is calling [AVPlayer play] whilst my screen is ALREADY locked. This ultimately results in no music being played.

Upvotes: 3

Views: 950

Answers (1)

Mick MacCallum
Mick MacCallum

Reputation: 130222

You need to tell your player to listen for control events:

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];
}
- (BOOL)canBecomeFirstResponder {
    return YES;
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
    [self resignFirstResponder];
}

Then you can act on them like so:

- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
    if (event.type == UIEventTypeRemoteControl) 
        {
        if (event.subtype == UIEventSubtypeRemoteControlPlay) 
            {
            [AVPlayer play];
            } 

        else if (event.subtype == UIEventSubtypeRemoteControlPause) 
            {
            [AVPlayer pause];
            } 
        else if (event.subtype == UIEventSubtypeRemoteControlTogglePlayPause) 
            {
                if (!AVPlayer.playing) 
                    {
                        [AVPlayer play];

                    } else if (AVPlayer.playing) 
                    {
                        [AVPlayer pause];
                    }
            }
        else if (event.subtype == UIEventSubtypeRemoteControlNextTrack)
            {
            [self myNextTrackMethod];
            }
        else if (event.subtype == UIEventSubtypeRemoteControlPreviousTrack)
            {
            [self myLastTrackMethod];
            }
        }
}

Upvotes: 4

Related Questions