在我的应用程序中,我有一个 AVAudioPlayer 的实例,它播放一系列mp3,通过initWithData
切换到下一个:
我想让用户继续听播放器,即使他关掉屏幕或转到后台。我知道,当用户点击它时,我可以使用remotecontrolevents
切换到其他音频,但是我可以自动切换,就像在iPod播放器中一样吗?
答案 0 :(得分:4)
您需要使用AVAudioPlayerDelegate
协议。首先将它包含在您的界面中:
@interface MyAppViewController : UIViewController <AVAudioPlayerDelegate> {
AVAudioPlayer *yourPlayer;
}
@property (nonatomic, retain) AVAudioPlayer *yourPlayer;
然后在您的实施中:
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
//This method is called once the file has finished playing
//Insert code here to play the next file
}
不要忘记在delegate
方法中(或您决定放置它的地方)将yourPlayer
的{{1}}设置为self
:
viewDidLoad
您还需要将 info.plist 中的必需背景模式更改为应用播放音频
不要忘记取消注册远程控制事件(- (void)viewDidLoad {
[super viewDidLoad]
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
if ([[UIApplication sharedApplication] respondsToSelector:@selector(beginReceivingRemoteControlEvents)]){
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
}
self.yourPlayer = [[AVAudioPlayer alloc] init];
self.yourPlayer.delegate = self;
}
):
viewDidUnload