Search code examples
iosobjective-cavaudioplayermpmediaitem

Update Song time label


The app is a music player, and I need to show a trackTimeLabel that updates the playback duration during the song.

So, update the label every second with the playback track time duration.

Right now I'm doing a hack where I am just counting seconds that have nothing to do with the song, but that's not a good solution:

- (void)viewWillAppear:(BOOL)animated {
    currentItem = [musicPlayer nowPlayingItem];
    _titleLabel.text = [self currentItemValue:MPMediaItemPropertyTitle];
    NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timerDidTick:) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}

-(void) timerDidTick:(NSTimer*) theTimer{
    long currentPlaybackTime = musicPlayer.currentPlaybackTime;
    int currentHours = (int)(currentPlaybackTime / 3600);                         
    int currentMinutes = (int)((currentPlaybackTime / 60) - currentHours*60);     // Whole minutes
    int currentSeconds = (currentPlaybackTime % 60);                        
    _trackTimeLabel.text = [NSString stringWithFormat:@"%i:%02d:%02d", currentHours, currentMinutes, currentSeconds];
}

Apple has a MPMediaItem class which I can get a MPMediaItemPropertyPlaybackDuration for the track, but I can't seem to get anything working with that.


Solution

  • Step 1

    In your ViewController.h

    #import <AVFoundation/AVFoundation.h>
    #import <MediaPlayer/MediaPlayer.h>
    
    @interface ViewController : UIViewController
    {
        AVAudioPlayer * player;
    }
    
    @property (weak, nonatomic) IBOutlet UISlider *seekSlider;
    
    @property (weak, nonatomic) IBOutlet UILabel *lbl;
    

    Step 2

    In your ViewController.m

        - (void)viewDidLoad {
        NSURL * fileURL = [[NSBundle mainBundle] URLForResource:@"01 - Saturday Saturday - DownloadMing.SE" withExtension:@"mp3"];
    
        NSError * error = nil;
    
        player = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL error:&error];
    
    
    
        if(error)
            NSLog(@"Error : %@ ", error);
    
        [player prepareToPlay];
    
        player.volume = 0.5;
    
        self.seekSlider.maximumValue = player.duration;
    }
    -(void)timerMethod:(NSTimer *)timer
    {
    
    
        float progress = player.currentTime;
        //    if(!self.seekSlider.isFocused)
        self.seekSlider.value = progress;
    
        _lbl.text = [NSString stringWithFormat:@"%.f:%.2d", (progress / 60), ((int)progress % 60 )];
    }
    
    
    - (void)didReceiveMemoryWarning
    {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    - (IBAction)play_pause_clicked:(id)sender {
    
    
        if(player.playing)
        {
            [player pause];
            [(UIButton*)sender setTitle:@"Play" forState:UIControlStateNormal];
        }
        else
        {
            [player play];
            [(UIButton*)sender setTitle:@"Pause" forState:UIControlStateNormal];
    
            [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerMethod:) userInfo:nil repeats:YES];
    
    
        }
    
    
    }
    
    
    - (IBAction)seekPlayer:(id)sender {
    
        player.currentTime = [(UISlider*)sender value];
    
    
    }
    - (IBAction)changeVolume:(id)sender {
    
        player.volume = [(UISlider*)sender value];
    
    
    }
    

    This is perfect working code for me... Try this, I hope, this will help you :)