1

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

nzs
  • 3,252
  • 17
  • 22
user2326633
  • 33
  • 1
  • 7

1 Answers1

3

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

nzs
  • 3,252
  • 17
  • 22
  • Thank you for taking all this time to make this, its perfect but I know how to do it with the AVFoundation framework, my problem is with the media framework where you access the music from your library, but Im definitely marking this as answered for the time you took for me I thank you a lot and hope you have another solution for me great answer really :) – user2326633 Apr 28 '13 at 15:26
  • Thank you for the great answer. I notice you check to make sure the player was created okay and then output an error message if it is, but then you continue to use the player as if it was successful regardless of if it was or wasn't. Shouldn't those lines under where you output the error be in a conditional block so they don't get used if `player` is nil? – primehalo Dec 08 '15 at 04:21