当ViewController加载时,UISlider的AVPlayer currentTime更新

时间:2013-10-01 03:06:52

标签: ios avfoundation avplayer uislider

我在AVPlayer播放歌曲。我为我的媒体播放器和初始化创建了一个单独的视图控制器,我在播放器中使用的所有方法(播放,暂停,重复,随机播放)都在同一个视图控制器中。

我像这样更新一个滑块:

[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;
}

一旦我走出viewcontroller,再来一次,歌曲正在播放,但问题是滑块没有更新。所以我创建了一个单例类来分配当前播放的歌曲细节。同样在滑块更新中,我为单例类变量设置了playerCurrentTime(slidercurrent值)。我分配的viewdidload方法就像这样:

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];
}

但滑块未更新。为什么这样以及如何解决这个问题?

2 个答案:

答案 0 :(得分:22)

您不应该使用计时器,AVPlayer提供您观察时间的API。

注册观察员(例如在viewWillAppear中),如下所示:

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...
}];

要取消注册观察者(例如在viewDidDisappear中),请执行:

[self.player removeTimeObserver:self.playbackTimeObserver];

希望有所帮助。

答案 1 :(得分:2)

Swift 3 版本。

注册观察员:

if let observer = self.playerObserver {
    self.player.removeTimeObserver(observer)
    self.playerObserver = nil
}

删除观察者:

{{1}}