2012-03-13 81 views
1

我正在開發一款iOS音頻播放器,並且我想實現一個進度條,用於指示正​​在播放的當前歌曲的進度。 在我的ViewController類中,我有兩個雙重實例 - 時間和持續時間,以及一個名爲background的AVAudioPlayer實例。更新iOS 5中的進度條

- (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; 
    } 
} 

任何人都可以解釋我做錯了什麼? 在此先感謝。

回答

9

您不會在播放過程中更新進度欄的進度。當您開始播放聲音時,您將進度條設置爲1,至2,至3,至4,至5 ...至100%。所有這些都不用離開當前的runloop。這意味着你只會看到最後一步,一個完整的進度條。

您應該使用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; 
+0

非常感謝你,它的工作原理! ;-) – nemesis 2012-03-13 19:28:57