I'm playing songs in AVPlayer
. I have created a separate view controller for my media player and initialization, and all the methods that I'm using for the player (play, pause, repeat, shuffle) are there in the same view controller.
I update a slider like this:
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(sliderUpdate:) userInfo:nil repeats:YES];`
- (void) sliderUpdate:(id) sender{
int currentTime = (int)((song.player.currentTime.value)/song.player.currentTime.timescale);
slider.value=currentTime;
NSLog(@"%i",currentTime);
song.currentTime=currentTime;
int currentPoint=(int)((song.player.currentTime.value)/song.player.currentTime.timescale);
int pointMins=(int)(currentPoint/60);
int pointSec=(int)(currentPoint%60);
NSString *strMinlabel=[NSString stringWithFormat:@"%02d:%02d",pointMins,pointSec];
lblSlidermin.text=strMinlabel;
song.strslidermin=strMinlabel;
}
Once I'm going out of the viewcontroller and when come again, song is playing but the problem is slider is not updating. So I created a singleton class to assign currently playing song details. Also inside the slider update I asigned playerCurrentTime
(slidercurrent value) for a singleton class variable. And my viewdidload
method I assigned like this:
if (song.isPlaying==NO) {
[self prePlaySong];
}else{
lblAlbum.text=song.currentAlbum;
lblArtist.text=song.currentArtist;
lblSong.text=song.currentSong;
slider.value=song.currentTime;
slider.maximumValue=song.sliderMax;
slider.minimumValue=song.sliderMin;
imgSong.image=song.songImage;
[btnMiddle setBackgroundImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal];
}
but slider is not getting updated. Why is that and how I can solve this problem?
Swift 3 version.
Register an observer:
Remove an obserber:
You should not use a timer for this,
AVPlayer
provides an API you observe the time.Register an observer (e.g. in
viewWillAppear
) like this:To unregister the observer (e.g. in
viewDidDisappear
), do:Hope that helps.