-->

我们如何处理耳机播放/暂停按钮事件前景的IOS(How can we handle headphon

2019-08-17 15:13发布

我有一个处理耳机播放/暂停按钮事件在前景中的要求。 我可以使用下面的代码来处理同样的场景在后台如何过

if ([[UIApplication sharedApplication] respondsToSelector:@selector(beginReceivingRemoteControlEvents)]){
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];
    [self becomeFirstResponder];
    NSLog(@"Responds!");
}

请解释或示例代码,如果可能的帮助。 我已经做了很多的研究,但没有帮助。

Answer 1:

还有就是要实现从耳机播放器控制的另一种方式。 使用MPRemoteCommandCenter tooglePlayPauseCommand。 苹果文档

[[MPRemoteCommandCenter sharedCommandCenter].togglePlayPauseCommand addTarget:self action:@selector(onTooglePlayPause)];


Answer 2:

您必须检查此条件:

  1. 编辑您的info.plist,规定你在后台做音频(UIBackgroundModes)以及前景。
  2. 实现这个功能:

     - (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; } } } 

......显然,替换“//插入代码”与任何功能是培训相关的您的应用程序。

3>最后,为了使上述函数的调用,在你的viewDidAppear事件插入此:

[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    if ([self canBecomeFirstResponder]) {
        [self becomeFirstResponder];
    }

还请访问以下链接: http://www.sagorin.org/2011/11/29/ios-playing-audio-in-background-audio/



Answer 3:

雨燕第2版slobodans的解决方案:

MPRemoteCommandCenter.sharedCommandCenter().togglePlayPauseCommand.addTarget(self, action: #selector(togglePlayStop(_:)));


文章来源: How can we handle headphone play/pause button events in foreground in ios