播放音频也可以使用AVPlayer
,因为音频没有画面,所以就不要创建AVPlayerLayer
,只需要一个avplayer就可以完成播放的事情
1、后台播放音频,需要在plist文件中添加如下字段:
添加键值 Required background modes
,设置值为 App plays audio or streams audio/video using AirPlay
2、代码中设置
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setActive:YES error:nil];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
上面代码一定要写,否则可能无法响应控制事件
如果AppDelegate
中没有注册响应后台控制,可以在播放器控制器中添加响应
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
3、响应控制
#pragma mark ----播放器外部控制----
- (BOOL)canResignFirstResponder {
return YES;
}
- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
switch (event.subtype) {
case UIEventSubtypeRemoteControlPlay:
{
//play
}
break;
case UIEventSubtypeRemoteControlPause:
{
//pause
}
break;
case UIEventSubtypeRemoteControlPreviousTrack:
{
//last
}
break;
case UIEventSubtypeRemoteControlNextTrack:
{
//next
}
break;
case UIEventSubtypeRemoteControlTogglePlayPause:
{
//暂停、播放切换
}
break;
default:
break;
}
}
event
中的subtype
便是点击控制中心的按钮的相应事件类型:
typedef NS_ENUM(NSInteger, UIEventSubtype) {
// available in iPhone OS 3.0
UIEventSubtypeNone = 0,
// for UIEventTypeMotion, available in iPhone OS 3.0
UIEventSubtypeMotionShake = 1,
// for UIEventTypeRemoteControl, available in iOS 4.0
UIEventSubtypeRemoteControlPlay = 100,//点击播放按钮或者耳机线控中间那个按钮
UIEventSubtypeRemoteControlPause = 101,//点击暂停按钮
UIEventSubtypeRemoteControlStop = 102,//点击停止按钮
UIEventSubtypeRemoteControlTogglePlayPause = 103,//点击播放与暂停开关按钮(iphone抽屉中使用这个)
UIEventSubtypeRemoteControlNextTrack = 104,//点击下一曲按钮或者耳机中间按钮两下
UIEventSubtypeRemoteControlPreviousTrack = 105,//点击上一曲按钮或者耳机中间按钮三下
UIEventSubtypeRemoteControlBeginSeekingBackward = 106,//快退开始 点击耳机中间按钮三下不放开
UIEventSubtypeRemoteControlEndSeekingBackward = 107,//快退结束 耳机快退控制松开后
UIEventSubtypeRemoteControlBeginSeekingForward = 108,//开始快进 耳机中间按钮两下不放开
UIEventSubtypeRemoteControlEndSeekingForward = 109,//快进结束 耳机快进操作松开后
};
4、设置后台信息及锁屏界面
NSMutableDictionary * audioInfo = [NSMutableDictionary dictionary];
//音乐的标题
[audioInfo setObject:@"标题" forKey:MPMediaItemPropertyTitle];
//音乐的艺术家
[audioInfo setObject:@"艺术家" forKey:MPMediaItemPropertyArtist];
//音乐的播放时间
[audioInfo setObject:@(self.playingTime) forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
//音乐的播放速度
[audioInfo setObject:@(1) forKey:MPNowPlayingInfoPropertyPlaybackRate];
//音乐的总时间
[audioInfo setObject:@(self.totalTime) forKey:MPMediaItemPropertyPlaybackDuration];
//音乐的封面
MPMediaItemArtwork * artwork = [[MPMediaItemArtwork alloc] initWithImage:@""];
[audioInfo setObject:artwork forKey:MPMediaItemPropertyArtwork];
//完成设置
[[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:audioInfo];
如果需要实时更新播放进度,就需要在播放器的回调中,每次执行这个方法,可以在info中只添加
MPNowPlayingInfoPropertyElapsedPlaybackTime
字段,其他的不用每次都发送(也可根据需求自行添加其他字段)
网友评论