AVPlayer currentTime update for a UISlider when ViewController load

iDia picture iDia · Oct 1, 2013 · Viewed 12.9k times · Source

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?

Answer

chris picture chris · Oct 2, 2013

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:

CMTime interval = CMTimeMakeWithSeconds(1.0, NSEC_PER_SEC); // 1 second
self.playbackTimeObserver =
    [self.player addPeriodicTimeObserverForInterval:interval 
                                              queue:NULL usingBlock:^(CMTime time) {
    // update slider value here...
}];

To unregister the observer (e.g. in viewDidDisappear), do:

[self.player removeTimeObserver:self.playbackTimeObserver];

Hope that helps.