在我的应用程序中,我想实现音乐播放,就像 iPod 音乐库一样,可以播放背景和远程控制。
我的应用程序是:在主页面中有几个项目的表格视图,选择音乐项目将进入音乐视图并显示用户下载的音乐。然后在此页面中用户可以选择要播放的歌曲。
我在单例中创建了一个自定义播放器类,以便音乐仍然可以播放离开音乐视图页面的事件。现在我的问题是如何实现远程控制。我使用Apple guide尝试过这种方式 。当应用程序位于音乐视图页面然后进入后台时,它确实有效。
但是,如果应用程序在其他页面并且正在播放音乐,则遥控器失败并且没有任何调用。
我的代码是这样的:
[self.navigationController pushViewController:musicViewController animated:YES];
MusicViewController 有一个单例播放器,就像:
@interface FWAudioPlayer : UIViewController// I also tried to subclass of UIResponder, and it didn't work either { NSUInteger currectIndex; NSMutableArray *_urlArray; NSMutableArray *randomArray; AVAudioPlayer *_player; id fwDelegate; } @property (nonatomic, retain) NSMutableArray *urlArray; @property (nonatomic, retain) NSMutableArray *randomArray; @property (nonatomic, retain) AVAudioPlayer *audioPlayer; @property (nonatomic, assign) id fwDelegate; @property (nonatomic, assign) NSUInteger currectIndex; @property (nonatomic, assign) BOOL shuffle; + (id)sharedAudioPlayerWithData:(NSData *)data error:(NSError **)error; + (id)sharedAudioPlayer; @end
当应用程序离开音乐查看页面时,我在这里做了某事
- (void)viewWillDisappear:(BOOL)animated { FWAudioPlayer *fwaudioPlayer = [FWAudioPlayer sharedAudioPlayer]; [fwaudioPlayer becomeFirstResponder]; }
顺便说一句,我已经在 AppDelegate 中设置了:
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
现在当应用离开音乐查看页面时,我可以找到[FWAudioPlayer canBecomeFirstResponder]
被调用的。然后我按一下遥控器,[FWAudioPlayer remoteControlReceivedWithEvent:]
是从来不叫的。然后我尝试在 AppDelegate 中接收远程控制事件。如果它可以在 AppDelegate 中接收事件,我可以分派事件处理并调用单例类。但是,它似乎永远不会在 AppDelegate 中被调用。
所以我想知道这里有什么问题。我的猜测是单例类FWAudioPlayer
不是真的UIViewController
,因为它不在应用程序的视图层次结构下。此外,当应用程序离开主页面等其他页面时,它MainViewController
是第一响应者,FWAudioPlayer
永远无法获得远程事件。
如果我是对的,我怎样才能实现一个与 iPod 音乐功能相同的音乐播放器,尤其是具有后台播放和远程控制功能?
如果我的猜测是错误的,如何使它(单例类)接收远程事件?
谢谢!!