avaudioplayer在背景中播放音乐

时间:2014-10-22 08:52:32

标签: xcode

我在后台有AVAudioPlayer的问题,一切正常但是当我在锁定屏幕中有控件并且我点击暂停按钮时控件会收到事件但是带控件的锁定屏幕会消失。我希望锁定屏幕保留在音乐应用程序等控件中。

我将这些行放在viewDidLoad

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

然后:

-(void)viewDidAppear:(BOOL)animated{


   [[UIApplication sharedApplication]beginReceivingRemoteControlEvents];
   [self becomeFirstResponder];
}

-(BOOL)canBecomeFirstResponder{ return YES; }

- (void)viewWillDisappear:(BOOL)animated {


    //End recieving events
    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
    [self resignFirstResponder];

     [super viewWillDisappear:animated];
}

- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
    //if it is a remote control event handle it correctly

    if (event.type == UIEventTypeRemoteControl) {
        if (event.subtype == UIEventSubtypeRemoteControlPause) {

            [self.playButton setBackgroundImage:[UIImage imageNamed:@"play_icon.png"]
                                       forState:UIControlStateNormal];
            [self.audioPlayer pauseAudio];
            self.isPaused = FALSE;
        }
        else if (event.subtype == UIEventSubtypeRemoteControlPlay){

            if (!self.isPaused) {
                [self.playButton setBackgroundImage:[UIImage imageNamed:@"pause.png"]
                                           forState:UIControlStateNormal];

                //start a timer to update the time label display
                self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                              target:self
                                                            selector:@selector(updateTime:)
                                                            userInfo:nil
                                                             repeats:YES];

                [self.audioPlayer playAudio];
                self.isPaused = TRUE;

            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我找到了解决方案!!

使用此属性:         @property MPNowPlayingInfoCenter * nowPlayingInfo;

我必须在viewDidLoad上添加这些行:

    [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo=[NSDictionary dictionaryWithObject:@1.0f forKey:MPNowPlayingInfoPropertyPlaybackRate];