Question

I am trying to implement AVAudioPlayer to start, pause, stop, rewind and forward an audio with progress bar. I implemented start successfully but when I pause the audio and play again, it restarts from beginning, instead of resuming from whrer it was left.

Following is the code:

    - (IBAction)btnPlay_click:(id)sender {

    UIButton *btn = (UIButton *)sender;
    if([btn backgroundImageForState:UIControlStateNormal] == [UIImage imageNamed:@"play.png"]){
        [self.audioPlayer setDelegate:self];
    NSString *audioPath = [NSString stringWithFormat:@"%@/%@",self.strBookPath, [arrMP3Files objectAtIndex:currentPage+1]];
    NSURL *audioURL = [NSURL fileURLWithPath:audioPath];
    NSError *error;
    self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:&error];
        [self.audioPlayer prepareToPlay];
    [self.audioPlayer play];
        [btn setBackgroundImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal];
    } else {
        [self.audioPlayer pause];
        [btn setBackgroundImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
    }
}

Where am I getting wrong? How do I solve this?

Was it helpful?

Solution

I think you should update your code as like below

- (IBAction)btnPlay_click:(UIButton *)sender
{

    if (!self.audioPlayer)
    {
        NSString *audioPath = [NSString stringWithFormat:@"%@/%@",self.strBookPath, [arrMP3Files objectAtIndex:currentPage+1]];

        NSURL *audioURL = [NSURL fileURLWithPath:audioPath];

        NSError *error;

        self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:&error];

        [self.audioPlayer setDelegate:self];

        [self.audioPlayer prepareToPlay];
    }

    if(![self.audioPlayer isPlaying])
    {

        [self.audioPlayer play];

        [btn setBackgroundImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal];
    }
    else
    {
        [self.audioPlayer pause];

        [btn setBackgroundImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top