最近適配耳機(jī)線控,記錄一下問題
首先,耳機(jī)線控三要素:
1、開啟接受耳機(jī)線控
~~~~
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
~~~~
2、成為第一響應(yīng)者
~~~~
[self becomeFirstResponder];
重寫響應(yīng)方法
-(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(@"單擊,再按下不放,松開時(shí):109");
}break;
default:
break;
}
}
}
~~~~
為了保證這個(gè)方法的可行性,最好寫在appdelegate 或者 rootController里
4、app是持有播放權(quán)限的,即沒有被別的app搶走播放權(quán)限,也就是在系統(tǒng)中心展示的是我們app的播放信息,當(dāng)然不添加信息在控制中心的話,如果能確定是自己的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有一個(gè)比較坑的問題是,必須在playback模式下才可以接受到響應(yīng)事件,通常我們使用的權(quán)限都是playandrecord,這個(gè)是可以接受到線控耳機(jī)的響應(yīng)事件,但是接收AirPods的事件。
如果要更加精細(xì)的操作,了解下MPNowPlayingInfoCenter和MPRemoteCommandCenter,iOS7.0之后推出的