设备锁定时从iPod库播放音频

时间:2012-07-17 04:07:13

标签: iphone objective-c ios avaudioplayer avplayer

只是一个简单的问题。

我已经设置了我的程序,以便能够在后台播放AVAudioPlayerAVPlayer,这很正常。我可以播放一首歌,锁定我的屏幕,声音将继续播放。

我遇到的问题是在我的屏幕已被锁定时调用[AVPlayer play]。这最终导致没有播放音乐。

1 个答案:

答案 0 :(得分:4)

你需要告诉你的播放器听取控制事件:

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

然后你可以这样对他们采取行动:

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