Reputation: 1351
I am developing an iOS audio player, and I want to implement a progress bar that will indicate the progress of the current song which is playing. In my ViewController class, I have 2 double instances - time and duration, and a AVAudioPlayer instance called background.
- (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;
}
}
Could anyone explain what I am doing wrong? Thanks in advance.
Upvotes: 1
Views: 7648
Reputation: 90127
you don't update the progress of the progress bar during playback. When you start to play the sound you set the progress bar to 1, to 2, to 3, to 4, to 5... to 100%. All without leaving the current runloop. Which means you will only see the last step, a full progress bar.
You should use a NSTimer to update the progress bar. Something like this:
- (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];
}
when you stop playing invalidate the timer.
[self.timer invalidate];
self.timer = nil;
Upvotes: 9