gpt4 book ai didi

objective-c - 无法在 iOS 中开始接收 RemoteControlEvents

转载 作者:可可西里 更新时间:2023-11-01 03:06:03 26 4
gpt4 key购买 nike

在我的应用程序中,我想让用户在后台控制音频播放。我在 .plist 中设置了 backGround 模式,并按照我想要的方式在 bg 中播放。但是我无法通过触摸控制按钮获得任何响应。

我这样设置AudioSession

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

然后,在放置我的播放器的 viewContoller 中,我像这样 beginReceivingRemoteControlEvents

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

然后打印 Respons!

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

    - (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上写一个category让它成为第一响应者,但是没用

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

为什么会这样?

解决方案这就是解决我的问题的方法 Entering background on iOS4 to play audio

最佳答案

我在我的项目中做了同样的工作,它运行良好。请按照此操作,也许它会对您有所帮助。更改事件名称等。在我的代码中,_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;
}
}

关于objective-c - 无法在 iOS 中开始接收 RemoteControlEvents,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10276096/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com