views:

621

answers:

2

hi everyone,

I'm trying to implement a little function in my app. I am currently playing sounds as AVAudioPlayers and that works fine. What I would like to add is to control the sound's position (currentTime) with an UISlider: is there a simple way to do it ?

I looked at an Apple project but it was quite messy....have you got samples or suggestions ?

Thanks to everyone in advance

+2  A: 

Shouldn't be a problem - just set the slider to continuous and set the max value to your player's duration after loading your sound file.

Edit

I just did this and it works for me...

- (IBAction)slide {
    player.currentTime = slider.value;
}

- (void)updateTime:(NSTimer *)timer {
    slider.value = player.currentTime;
}

- (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];
    slider.maximumValue = [player duration];
    slider.value = 0.0;

    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTime:) userInfo:nil repeats:YES];  
    [player play];
}

The slider is configured in IB, as is a button to start playing.

Paul Lynch
I coded like this, it builds correctly but it doesn't work: _progressBar.continuous = YES; _progressBar.value = [suono01 currentTime]; _progressBar.minimumValue = 0.0; _progressBar.maximumValue = suono01.duration;
David Pollak
+2  A: 

To extend on paull's answer, you'd set the slider to be continuous with a maximum value of your audio player's duration, then add some object of yours (probably the view controller) as a target for the slider's UIControlEventValueChanged event; when you receive the action message, you'd then set the AVAudioPlayer's currentTime property to the slider's value. You might also want to use an NSTimer to update the slider's value as the audio player plays; +scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: is the easiest way to do that.

Noah Witherspoon
I'm really new to iphone development, so I gently ask you to follow me while doing everything....so in the viewDidLoad method I start the audio, and added this: _progressBar.continuous = YES; _progressBar.minimumValue = 0.0; _progressBar.maximumValue = suono01.duration; [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(onTimer) userInfo:nil repeats:YES]; Now I what do I need to do use UIControlEventValueChanged ?
David Pollak
I continued like this but if I move the slider, currentTime doesn't move:- (void)onTimer{ UISlider *sliderozzo = _progressBar; [sliderozzo addTarget:self action:@selector(buttonClicked) forControlEvents:UIControlEventValueChanged]; _progressBar.value = [suono01 currentTime];}- (void)buttonClicked{ _progressBar.value = [suono01 currentTime];}
David Pollak