Search code examples
iphonexcodeios6avfoundationuiprogressview

UIProgressView with media framework for music length (Xcode)


Can someone give a full example of how to get the UIProgressView to work with the media framework for music length please, I cant get it to work with ios6 for some reason


Solution

  • I quicly set up a simple project to demonstrate this for you.

    Add two GUI element to your ViewController.xib: a Button and a Progress View. We will use the button the start the sound playing.

    Use this in your ViewController.h:

    #import <UIKit/UIKit.h>
    #import <AVFoundation/AVFoundation.h>
    
    @interface ViewController : UIViewController {
        AVAudioPlayer *player;
    }
    
    @property IBOutlet UIProgressView *progressbar;
    - (IBAction)play:(id)sender;
    
    @end
    

    After this you are able to connect your ViewController.xib outlets/actions to the properly set up parts in ViewController.h. Connect the button's Touch Up Inside event with the File's Owner link (under Placeholders) and you can select the play method. Connect the progress view's New Referencing Outlet with the File's Owner link and you can select progressbar.

    Then you can use this code in your ViewController.m:

    - (IBAction)play:(id)sender {
        NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"sound.caf" ofType:nil]];
        NSError *error;
        player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
        if (!player) NSLog(@"Error: %@", error);
        [player prepareToPlay];
        [progressbar setProgress:0.0];
    
        [NSTimer scheduledTimerWithTimeInterval:1.0/60.0 target:self selector:@selector(updateTime:) userInfo:nil repeats:YES];
        [player play];
    }
    
    - (void)updateTime:(NSTimer *)timer {
        [progressbar setProgress:(player.currentTime/player.duration)];
    }
    

    Dont forget to add your sound.caf in your project.

    enter image description here