更新UISlider进度条播放音频时的当前时间和持续时间

时间:2013-01-30 23:35:15

标签: iphone ios6

当播放音频时,在UIToolbar上有一个UISlider ProgressBar,希望UISlider ProgressBar显示音频文件的持续时间和音频文件的当前时间。

 - (void)playAction:(id)sender
 {
if([player isPlaying])
{
    [sender setImage:[UIImage imageNamed:@"1play.png"] forState:UIControlStateSelected];
    [player pause];
    //[self pauseTimer];


}else{
    [sender setImage:[UIImage imageNamed:@"audiopause.png"] forState:UIControlStateNormal];
    [player play];
    //[self resumeTimer];


    }

[self updateProgressBar:timer];

}


- (void)updateProgressBar:(NSTimer *)timer
{
NSTimeInterval playTime = [self.player currentTime];
NSTimeInterval duration = [self.player duration];
float progress = playTime/duration;
[_progressBar setProgress:progress];

}

但它没有用。

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

你可能想要使用计时器调用updateProgressBar方法,而不是你现在正在做的事情(在playAction方法中调用它)。相反,您可以使用playAction方法创建调用updateProgressBar的计时器,或暂停/停止现有计时器。

看起来你已经有了一个实例变量来跟踪计时器,这很好。以下是创建新计时器的方法:

[timer invalidate]; // stop the old timer

// this timer runs once per second, perhaps you want to make it something shorter which would look less choppy
NSTimer *progressTimer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(updateProgressBar:) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:progressTimer forMode:NSRunLoopCommonModes];
timer = progressTimer;

如果您有暂停音频的方法,也可以在那里使计时器无效。

[timer invalidate];
timer = nil;

总而言之,在您的代码中,这看起来像是:

 - (void)playAction:(id)sender
 {
    if([player isPlaying])
    {
        [sender setImage:[UIImage imageNamed:@"1play.png"] forState:UIControlStateSelected];
        [player pause];

        [timer invalidate];
        timer = nil;

    } else {

        [sender setImage:[UIImage imageNamed:@"audiopause.png"] forState:UIControlStateNormal];
        [player play];

        [timer invalidate];

        NSTimer *progressTimer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(updateProgressBar:) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:progressTimer forMode:NSRunLoopCommonModes];
        timer = progressTimer;

    }

}

- (void)updateProgressBar:(NSTimer *)timer
{
    NSTimeInterval playTime = [self.player currentTime];
    NSTimeInterval duration = [self.player duration];
    float progress = playTime/duration;
    [_progressBar setProgress:progress];

}

答案 1 :(得分:1)

试试这个: 这是用于更新滑块..

[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateSlider) userInfo:nil repeats:YES];
        slider.maximumValue = avAudioPlayer.duration;

        [slider addTarget:self action:@selector(sliderChanged:) forControlEvents:UIControlEventValueChanged];

- (void)updateSlider {

    slider.value = avAudioPlayer.currentTime;
}

- (IBAction)sliderChanged:(UISlider *)sender {

    [avAudioPlayer stop];
    [avAudioPlayer setCurrentTime:slider.value];
    [avAudioPlayer prepareToPlay];
    [avAudioPlayer play];
}