Im using AVPlayer to play songs from urls, I initialized and allocate it in my viewcontroller, now I have a problem,when I navigate to another view controller and back to the main player playing song details and slider update should be remain but the problem is when I navigate to the main player again playing details and slider update not happening but song is continuously playing. How I can avoid this and can anyone show me some example. Do I need to create a singleton class? If so how to create a singleton class for the AVPlayer?
Solution 1: You should update the UI also in viewWillAppear of your PlayerViewController. Song continues to play because you are not going back from or deallocating your PlayerViewController. If you pop or dismiss PlayerViewController , then this solution will not work.
Solution 2: Create A Singleton class having AVAudioPlayer instance in it. e.g
MediaManager.h
@interface MediaManager : NSObject{
}
+(MediaManager *)sharedInstance;
-(void)playWithURL:(NSURL *)url;
-(float)currentPlaybackTime;
@end
MediaManager.m
static MediaManager *sharedInstance = nil;
@interface MediaManager (){
AVAudioPlayer *audioPlayer;
}
@end
@implementation MediaManager
-(id)init{
if(self = [super init]){
}
return self;
}
+(MediaManager *)sharedInstance{
//create an instance if not already else return
if(!sharedInstance){
sharedInstance = [[[self class] alloc] init];
}
return sharedInstance;
}
-(void)playWithURL:(NSURL *)url{
NSError *error = nil;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
if(error == nil){
[audioPlayer play];
}
}
-(float)currentPlaybackTime{
return audioPlayer.currentTime;
}
@end
Add other necessary methods in it like "stopPlayer" etc.
Sample Method Call
[[MediaManager sharedInstance] playWithURL:url];
float currentTime = [[MediaManager sharedInstance] currentPlaybackTime];
// Update slider
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With