iphone - 在iOS 5中更新进度条

标签 iphone ios progress-bar avaudioplayer

我正在开发一个iOS音频播放器,并且想要实现一个进度条,该进度条将指示正在播放的当前歌曲的进度。
在我的ViewController类中,我有2个双实例-时间和持续时间,以及一个称为背景的AVAudioPlayer实例。

- (IBAction)play:(id)sender {
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"some_song" ofType:@"mp3"];
    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath];
    background = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
    background.delegate = self;
    [background setNumberOfLoops:1];
    [background setVolume:0.5];
    [background play];
    time = 0;
    duration = [background duration];
    while(time < duration){
        [progressBar setProgress: (double) time/duration animated:YES];
        time += 1; 
    } 
}

谁能解释我在做什么错?
提前致谢。

最佳答案

您不会在播放过程中更新进度条的进度。当您开始播放声音时,将进度条设置为1、2、3、4、5 ...到100%。全部都没有离开当前的运行循环。这意味着您只会看到最后一步,即完整的进度栏。

您应该使用NSTimer更新进度条。像这样:

- (IBAction)play:(id)sender {
    /* ... */
    [self.player play];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.23 target:self selector:@selector(updateProgressBar:) userInfo:nil repeats:YES];
}

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

当您停止播放时,会使计时器无效。
[self.timer invalidate];
self.timer = nil;

关于iphone - 在iOS 5中更新进度条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9690411/

相关文章:

ios - 如何从locationManager获取viewDidLoad的坐标?

ios - 文本字段崩溃成为使用 pickerview 的第一响应者

ios - 如何检测用户何时退出 iOS 上的 YouTube 播放器 View ?

objective-c - iOS 相当于 MacOS NSAttributedString initWithRTF

iphone - 为什么 UITableViewController self.tableView 属性在 UIPopoverController 中呈现时为 Nil?

android - 如何为移动应用程序创建演示

visual-c++ - 使用 Direct2D 绘制圆形进度条

c++ - 文件保存过程中的进度

c# - 如何在 C# WPF 应用程序中获取 FFMPEG 转换进度到进度条?

iphone - iphone有没有轻量级的http请求库?