无法开始在 iOS 中接收远程控制事件

2024-01-08

在我的应用程序中,我想让用户控制后台音频播放。我在 .plist 中设置了背景模式,并在背景中设置了播放模式,就像我想要的那样。但是我无法通过触摸控制按钮得到任何响应。

我设置了AudioSession像这样

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance]setActive:YES error:nil];

然后,在我的播放器所在的 viewController 中我beginReceivingRemoteControlEvents像这样

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

它打印Responds!

但问题是这个方法永远不会被调用

    - (void)remoteControlReceivedWithEvent:(UIEvent *)event
{
    NSLog(@"Where is my event?");
    if(event.type == UIEventTypeRemoteControl)
    {
        switch (event.subtype) {
            case UIEventSubtypeRemoteControlTogglePlayPause:
                NSLog(@"Pause");
                [self playWords:playButton];
                break;
            case UIEventSubtypeRemoteControlNextTrack:
                NSLog(@"Next");
                [self next];
                break;
            case UIEventSubtypeRemoteControlPreviousTrack:
                NSLog(@"Prev");
                [self prev];
                break;

        }
    }

我什至尝试写一个类别UIApplication让它成为第一响应者,但这并没有帮助

@implementation UIApplication (RemoteEvents)
-(BOOL)canBecomeFirstResponder
{
    return YES;
}
@end

为什么会发生这种情况?

SOLUTION这就是解决我的问题的方法iOS4进入后台播放音频 https://stackoverflow.com/questions/3161635/entering-background-on-ios4-to-play-audio/3161899#3161899


我在我的项目中做了同样的工作,效果很好。请遵循此,也许会对您有所帮助。更改事件名称等。在我的代码中,_audio 是 AVAudioPlayer 的对象。

- (void)viewDidLoad {
    NSError *setCategoryErr = nil;
    NSError *activationErr  = nil;
    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &setCategoryErr];
    [[AVAudioSession sharedInstance] setActive: YES error: &activationErr];
}

- (void)viewWillAppear {

      [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];
}


- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
    switch (event.subtype) {
        case UIEventSubtypeRemoteControlPlay:
            [_audio play];
            break;
        case UIEventSubtypeRemoteControlPause:
            [_audio pause];
            break;
        default:
            break;
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

无法开始在 iOS 中接收远程控制事件 的相关文章

随机推荐