在后台播放一系列音频文件

时间:2012-04-15 11:59:25

标签: objective-c ios background avfoundation avaudioplayer

在我的应用程序中,我有一个 AVAudioPlayer 的实例,它播放一系列mp3,通过initWithData切换到下一个:

我想让用户继续听播放器,即使他关掉屏幕或转到后台。我知道,当用户点击它时,我可以使用remotecontrolevents切换到其他音频,但是我可以自动切换,就像在iPod播放器中一样吗?

1 个答案:

答案 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