最近适配耳机线控,记录一下问题
首先,耳机线控三要素:
1、开启接受耳机线控
~~~~
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
~~~~
2、成为第一响应者
~~~~
[self becomeFirstResponder];
重写响应方法
-(BOOL)canBecomeFirstResponder{
return YES;
}
~~~~
3、重写UIResponder方法
~~~~
//received remote event
-(void)remoteControlReceivedWithEvent:(UIEvent *)event{
NSLog(@"event tyipe:::%ld subtype:::%ld",(long)event.type,(long)event.subtype);
//type==2 subtype==单击暂停键:103,双击暂停键104
if (event.type == UIEventTypeRemoteControl) {
switch (event.subtype) {
case UIEventSubtypeRemoteControlPlay:{
NSLog(@"play---------");
}break;
case UIEventSubtypeRemoteControlPause:{
NSLog(@"Pause---------");
}break;
case UIEventSubtypeRemoteControlStop:{
NSLog(@"Stop---------");
}break;
case UIEventSubtypeRemoteControlTogglePlayPause:{
//单击暂停键:103
NSLog(@"单击暂停键:103");
}break;
case UIEventSubtypeRemoteControlNextTrack:{
//双击暂停键:104
NSLog(@"双击暂停键:104");
}break;
case UIEventSubtypeRemoteControlPreviousTrack:{
NSLog(@"三击暂停键:105");
}break;
case UIEventSubtypeRemoteControlBeginSeekingForward:{
NSLog(@"单击,再按下不放:108");
}break;
case UIEventSubtypeRemoteControlEndSeekingForward:{
NSLog(@"单击,再按下不放,松开时:109");
}break;
default:
break;
}
}
}
~~~~
为了保证这个方法的可行性,最好写在appdelegate 或者 rootController里
4、app是持有播放权限的,即没有被别的app抢走播放权限,也就是在系统中心展示的是我们app的播放信息,当然不添加信息在控制中心的话,如果能确定是自己的app在播放也没问题,以下是添加播放信息在锁屏展示
~~~~
NSMutableDictionary *songInfo = [NSMutableDictionary dictionary];
//歌曲名称
[songInfo setObject:@"test" forKey:MPMediaItemPropertyTitle];
//演唱者
[songInfo setObject:@"Monkey" forKey:MPMediaItemPropertyArtist];
//图片
[songInfo setObject:[[MPMediaItemArtwork alloc] initWithImage:[UIImage imageNamed:@"MP.png"]] forKey:MPMediaItemPropertyArtwork];
[[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songInfo];
~~~~
最后适配一下AirPods,AirPods有一个比较坑的问题是,必须在playback模式下才可以接受到响应事件,通常我们使用的权限都是playandrecord,这个是可以接受到线控耳机的响应事件,但是接收AirPods的事件。
如果要更加精细的操作,了解下MPNowPlayingInfoCenter和MPRemoteCommandCenter,iOS7.0之后推出的
网友评论