nem*_*sis 1 iphone avaudioplayer ios progress-bar
我正在开发一个iOS音频播放器,我想实现一个进度条,它将指示正在播放的当前歌曲的进度.在我的ViewController类中,我有2个双实例 - 时间和持续时间,以及一个名为background的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;
}
}
Run Code Online (Sandbox Code Playgroud)
谁能解释我做错了什么?提前致谢.
在播放期间不更新进度条的进度.当您开始播放声音时,您将进度条设置为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];
}
Run Code Online (Sandbox Code Playgroud)
当你停止播放时,计时器无效.
[self.timer invalidate];
self.timer = nil;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7614 次 |
最近记录: |