AVAudioPlayer currentTime问题

时间:2009-05-19 13:28:09

标签: iphone audio-player

我正在尝试使用带滑块的AVAudioPlayer来搜索曲目(没有任何复杂的内容)。

但我有一个奇怪的行为......对于currentTime的某些值(介于0和trackDuration之间),玩家停止播放曲目,然后进入audioPlayerDidFinishPlaying:successfully: 成功地没有。它没有进入audioPlayerDecodeErrorDidOccur:error:

就像它无法读取我给它的时间。

例如,曲目的持续时间为:295.784424秒 我将currentTime设置为55.0s(即:54.963878或54.963900或54.987755等,当打印为%f时)。 当currentTime为54.987755时,总是会发生“崩溃”......我真的不明白为什么......

所以如果你有任何想法...... ^^

3 个答案:

答案 0 :(得分:5)

我也很难通过'AVAudioPlayer setCurrentTime:`

让音频跳过正常工作

经过大量的实验,我发现了一个在模拟器和设备上可靠运行的序列:(在OS3.1 +上测试)

// Skips to an audio position (in seconds) of the current file on the [AVAudioPlayer* audioPlayer] class instance
// This works correctly for a playing and paused audioPlayer
//
- (void) skipToSeconds:(float)position
{
    @synchronized(self) 
    {
        // Negative values skip to start of file
        if ( position<0.0f )
            position = 0.0f;

        // Rounds down to remove sub-second precision
        position = (int)position;

        // Prevent skipping past end of file
        if ( position>=(int)audioPlayer.duration )
        {
            NSLog( @"Audio: IGNORING skip to <%.02f> (past EOF) of <%.02f> seconds", position, audioPlayer.duration );
            return;
        }

        // See if playback is active prior to skipping
        BOOL skipWhilePlaying = audioPlayer.playing;

        // Perform skip
        NSLog( @"Audio: skip to <%.02f> of <%.02f> seconds", position, audioPlayer.duration );

        // NOTE: This stop,set,prepare,(play) sequence produces reliable results on the simulator and device.
        [audioPlayer stop];
        [audioPlayer setCurrentTime:position];
        [audioPlayer prepareToPlay];

        // Resume playback if it was active prior to skipping
        if ( skipWhilePlaying )
            [audioPlayer play];
    }
}  

答案 1 :(得分:1)

我尝试使用设备,这是仅在模拟器中出现的问题。 我的所有文件都在设备上播放得很好,我可以在其中轻松搜索。

我尝试过mp3,aac和wav。

答案 2 :(得分:1)

出于某种原因,当我收到此错误时,标志仍设置为YES。我已经设法通过检查currentTime与持续时间找到解决方法,并在currentTime不为0.0(声音结束)时立即重新启动播放器。我的所有测试都是在模拟器上完成的,因为我还没有在手机上测试的许可证。希望这可以帮助。请参阅编辑中的几个怪癖。

-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    if ([_player currentTime] != [_player duration] && [_player currentTime] != 0.0f) {
        [_player play];
        return;
    }
...

编辑:不幸的是,我在寻找声音的开头或结尾时(或者在非常小的增量中)仍然发现错误。我发现如果你创建处理这两个实例的特殊情况,你通常会被覆盖。您应该停止播放器,将currentTime设置为0.0然后如果寻找开头则再次启动播放器,或者如果您正在寻求结束(如果您实现它),则手动调用结束代理。

如果我找到更好的解决方案或在实际设备上获得更多反馈,我会更新。

相关问题