我要求在前台处理耳机播放/暂停按钮事件。我怎么能使用下面的代码
在后台处理相同的场景if ([[UIApplication sharedApplication] respondsToSelector:@selector(beginReceivingRemoteControlEvents)]){
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];
[self becomeFirstResponder];
NSLog(@"Responds!");
}
如果可能,请帮助解释或示例代码。我做了很多研究但没有帮助。
答案 0 :(得分:13)
还有另一种通过耳机实现播放器控制的方法。
使用MPRemoteCommandCenter
tooglePlayPauseCommand。
Apple documentation
[[MPRemoteCommandCenter sharedCommandCenter].togglePlayPauseCommand addTarget:self action:@selector(onTooglePlayPause)];
答案 1 :(得分:11)
您必须检查此条件:
实现此功能:
- (void)remoteControlReceivedWithEvent:(UIEvent *)theEvent
{
if (theEvent.type == UIEventTypeRemoteControl)
{
switch(theEvent.subtype) {
case UIEventSubtypeRemoteControlTogglePlayPause:
//Insert code
break;
case UIEventSubtypeRemoteControlPlay:
//Insert code
break;
case UIEventSubtypeRemoteControlPause:
// Insert code
break;
case UIEventSubtypeRemoteControlStop:
//Insert code.
break;
default:
return;
}
}
}
...显然,将“// insert code”替换为应用程序中相关的任何功能。
3>最后,为了调用上面的函数,将其插入到viewDidAppear事件中:
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
if ([self canBecomeFirstResponder]) {
[self becomeFirstResponder];
}
也请看这个链接: http://www.sagorin.org/2011/11/29/ios-playing-audio-in-background-audio/
答案 2 :(得分:4)
swbodans解决方案的swift 2版本:
MPRemoteCommandCenter.sharedCommandCenter().togglePlayPauseCommand.addTarget(self, action: #selector(togglePlayStop(_:)));