我正在开发一个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/