Playing AVAudio from iPod Library while device is locked

好久不见. 提交于 2019-12-23 18:39:16

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/11515883/playing-avaudio-from-ipod-library-while-device-is-locked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!