0

播放音频时在 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];

}

但它不起作用。

感谢帮助。

4

2 回答 2

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

}
于 2013-01-31T00:15:10.360 回答
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];
}
于 2013-01-31T04:49:03.777 回答