iOS:AVAudioPlayer在暂停后从头开始

时间:2014-05-08 11:41:11

标签: ios avaudioplayer

我正在尝试使用进度条实现AVAudioPlayer来启动,暂停,停止,快退和转发音频。 我实现了成功启动但是当我pause音频并再次播放时,它从头开始重新开始,而不是从它剩下的那个时候重新开始。

以下是代码:

    - (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];
    }
}

我哪里出错了?我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我认为您应该像下面一样更新您的代码

- (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];
    }
}
相关问题