简体   繁体   中英

UIProgressView not updating for Audio Player?

The ProgressView is not updating while playing the song. By reading from other post i have used an update method to update at each time interval.

- (void)viewDidLoad {
[super viewDidLoad];
NSString *filePath = [[NSBundle mainBundle]pathForResource:@"Fix you_Coldplay" ofType:@"mp3" inDirectory:@"Coldplay"];
NSLog(@"%@",filePath);
NSURL *url = [NSURL fileURLWithPath:filePath];
NSLog(@"%@",url);
musicPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
[musicPlayer prepareToPlay];
[trackProgress setProgress:0.0];
}

I have a play button which is also being used for calling updateTime: method.

- (IBAction)playButton:(id)sender {
[musicPlayer play];

[NSTimer scheduledTimerWithTimeInterval:0.0 target:self selector:@selector(updateTime:) userInfo:nil repeats:YES];

NSTimeInterval interval = musicPlayer.currentTime/musicPlayer.duration;
NSLog(@"%f",interval);
}

The updateTime: method

-(void)updateTime:(NSTimer *)timer {
trackProgress.progress = (musicPlayer.currentTime/musicPlayer.duration);
}

I am very new to programming and even stack overflow. This is the first question i am posting. Please help me and Thanks in advance.

First of all change timer value to:

//Change Value to 0.5 or 1 sec

[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(updateTime:) userInfo:nil repeats:YES];

Make sure you are setting trackProgress as 0 as initial value.

- (void)viewDidLoad {
    [super viewDidLoad];
    trackProgress.progress = 0.0;
   }

Hope this will resolve your issue.

Make sure to update the progress view on the main thread

-(void)updateTime:(NSTimer *)timer {
    dispatch_async(dispatch_get_main_queue(), ^{
        self.trackProgress.progress = (musicPlayer.currentTime/musicPlayer.duration);
    });
}

This might help. Create a Timer and add it to common runloop as shown below. Also keep a reference to timer so that it can be stopped later.

self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTime:) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM