我一直在寻找一种简单的方法来显示在UIProgressView中播放MP3的进度。我觉得它会涉及一个NSTimer对象,但我不确定如何实现它。
这是我到目前为止所拥有的。
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UISlider *VolumeLevel;
@property (weak, nonatomic) IBOutlet UIProgressView *progressBar;
@end
@implementation ViewController
AVAudioPlayer *player;
- (IBAction)play:(id)sender {
[player play];
}
- (IBAction)pause:(id)sender {
[player stop];
}
- (IBAction)volume:(id)sender {
player.volume = _VolumeLevel.value;
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *songURL =[NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:@"Gregory Is Here" ofType:@"mp3"]];
player =[[AVAudioPlayer alloc]initWithContentsOfURL:songURL error:nil];
player.volume = 0.5;
// Do any additional setup after loading the view, typically from a nib.
}
答案 0 :(得分:2)
使用NSTImer
,您可以执行以下操作:
- (IBAction)play:(id)sender {
[player play];
myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateProgressBar) userInfo:nil repeats:YES];
}
- (IBAction)pause:(id)sender {
[player stop];
[myTimer invalidate];
}
- (void)updateProgressBar {
float progress = player.currentTime / player.duration;
[myProgressBar setProgress:progress animated:YES];
}
您可以更改计时器timeInterval参数以更频繁地更新进度条(1.0表示1秒)。
答案 1 :(得分:0)
-(void) setPlayProgress
{
if (player.isPlaying) {
slider.value=abs(player.currentTime);
NSString *duration=[self getTimeStrFromInterval:player.duration-player.currentTime];
lblDuration.text=duration;
}
[self performSelector:@selector(setPlayProgress) withObject:nil afterDelay:0.1];
}
//显示时间
-(NSString *) getTimeStrFromInterval:(NSInteger) timeSinceStart{
int seconds = timeSinceStart;
int minutes = seconds/60;
int hours = minutes/60;
minutes = minutes%60;
seconds = seconds%60;
NSString *strHours;
NSString *strMinutes;
NSString *strSeconds;
strHours = [NSString stringWithFormat:@"%d",hours];
strMinutes = [NSString stringWithFormat:@"%d",minutes];
strSeconds = [NSString stringWithFormat:@"%d",seconds];
if (hours<10) {
strHours = [NSString stringWithFormat:@"0%d",hours];
}
if (minutes<10) {
strMinutes = [NSString stringWithFormat:@"0%d",minutes];
}
if (seconds<10) {
strSeconds = [NSString stringWithFormat:@"0%d",seconds];
}
NSString* intervalString;
if ([strHours intValue]>0) {
intervalString = [NSString stringWithFormat:@"%@:%@:%@",strHours,strMinutes,strSeconds];
}
else{
intervalString = [NSString stringWithFormat:@"%@:%@",strMinutes,strSeconds];
}
return intervalString;
}