Reputation: 5966
In my app i have an instance of AVAudioPlayer, that plays a sequence of mp3's ,switching to the next one by initWithData
:
I want to let the user continue listening to the player even if he switchs off the screen or goes to the background. I know, that i can use remotecontrolevents
to switch to the other audio when the user taps it, but can i make it switch automaticly,just like in iPod player?
Upvotes: 0
Views: 1692
Reputation: 6039
You need to use the AVAudioPlayerDelegate
protocols. First include it in your interface:
@interface MyAppViewController : UIViewController <AVAudioPlayerDelegate> {
AVAudioPlayer *yourPlayer;
}
@property (nonatomic, retain) AVAudioPlayer *yourPlayer;
Then in your implementation:
- (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
}
Don't forget to set the delegate
of yourPlayer
to self
in your viewDidLoad
method (or where ever you decide to put it):
- (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;
}
You'll also need to change Required Background Modes in your info.plist to App plays audio
Don't forget to unregister the remote control events (viewDidUnload
):
[[UIApplication sharedApplication] endReceivingRemoteControlEvents]
Upvotes: 4