AVPlayer后台播放实现

实现后台播放的步骤

一: 在appDelegate中通知app支持后台播放

二:在info.plist文件中添加一个key项,防止程序进入后台时程序被 suspend

三:在播放控制界面接受远程控制

四:对远程控制事件作出相应的操作

实现步骤

第一步:在appDelegate中通知app支持后台播放


// 告诉app支持后台播放

AVAudioSession *audioSession = [AVAudioSession sharedInstance];

[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];

[audioSession setActive:YES error:nil];

第二步:在info.plist文件中添加一个key项

这里写图片描述

在这个时候你的app就可以后台就行播放了 当时要想在手机的上拉菜单中对app进行控制就要添加以下代码

第三步:在播放控制界面接受远程控制


- (void)viewWillAppear:(BOOL)animated

{

[super viewWillAppear:YES];

// 开始接受远程控制

[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

[self becomeFirstResponder];

}

- (void)viewWillDisappear:(BOOL)animated

{

// 接触远程控制

[[UIApplication sharedApplication] endReceivingRemoteControlEvents];

[self resignFirstResponder];

}

// 重写父类成为响应者方法

- (BOOL)canBecomeFirstResponder

{

return YES;

}

第四步:对远程控制事件作出相应的操作


//重写父类方法,接受外部事件的处理

- (void) remoteControlReceivedWithEvent: (UIEvent *) receivedEvent {

if (receivedEvent.type == UIEventTypeRemoteControl) {

switch (receivedEvent.subtype) { // 得到事件类型

case UIEventSubtypeRemoteControlTogglePlayPause: // 暂停 ios6

[self actionStopButton:self.musicViewNew.stopButton]; // 调用你所在项目的暂停按钮的响应方法 下面的也是如此

break;

case UIEventSubtypeRemoteControlPreviousTrack:  // 上一首

[self actionUpButton:self.musicViewNew.upMusicButton];

break;

case UIEventSubtypeRemoteControlNextTrack: // 下一首

[self actionDownButton:self.musicViewNew.downMusicButton];

break;

case UIEventSubtypeRemoteControlPlay: //播放

[self actionStopButton:self.musicViewNew.stopButton];

break;

case UIEventSubtypeRemoteControlPause: // 暂停 ios7

[self actionStopButton:self.musicViewNew.stopButton];

break;

default:

break;

}

}

}

这样你的简单的播放音乐的app后台播放就算完成了,如果想理解锁屏后手机显示当前播放音乐的专辑以及照片的操作,且听下回分解~

你可能感兴趣的:(AVPlayer后台播放实现)