检查音频是否已在iOS中播放

时间:2013-03-19 15:19:38

标签: ios audio avfoundation

我想检查音频是否已播放完毕。如果是这样,我需要将按钮更改为播放按钮而不是暂停按钮。我如何在iOS中做到这一点?

我的代码如下所示:

-(void)playAudioFile:(BOOL)status
{
    NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"audio" ofType:@"mp3"];
    NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];


    NSError *error;

    if(status)
    {

        if(!audioPlayer)
        {
            audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:&error];
            audioPlayer.currentTime = currentPlayTime;
            audioPlayer.numberOfLoops = 0; //Infinite
            audioDuration = audioPlayer.duration;

            audioPlaySlider.minimumValue = 0;
            audioPlaySlider.maximumValue = audioDuration;
            audioPlaySlider.value = currentPlayTime;

            [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(audioTimer:) userInfo:[NSDictionary dictionaryWithObject:audioPlayer forKey:@"playerObject"] repeats:YES];
        }

        [audioPlayer play];

        if([audioPlayer rate] != 1.0 )
        {
            [audioPlayer play];
        }
        else
        {
            [self->audioPlayBtn setBackgroundImage:[UIImage imageNamed:@"playBtn.png"] forState:UIControlStateNormal];
        }


        NSLog(@"Play duration : %f",audioDuration);
    }
    else
    {
        if(audioPlayer && audioPlayer.playing)
        {
            [audioPlayer pause];                
        }
    }

    NSLog(@"Error for file : %@",error);

}

我试过了:

            if([audioPlayer rate] != 1.0 )
            {
                [audioPlayer play];
            }
            else
            {
                [self->audioPlayBtn setBackgroundImage:[UIImage imageNamed:@"playBtn.png"] forState:UIControlStateNormal];
            }

但不工作..需要一些指导......

1 个答案:

答案 0 :(得分:1)

使用AVAudioPlayerDelegate的方法

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag

带有audioplayer实例的viewcontroller / class必须是音频播放器的委托。当音频播放器完成播放时,将调用该方法。

http://developer.apple.com/library/ios/#documentation/AVFoundation/Reference/AVAudioPlayerDelegateProtocolReference/Reference/Reference.html