如何在iOS上使用AVAudioPlayer播放指定持续时间的声音?

我想在IOS的声音文件中播放指定的时间。 我在AVAudioPlayerfind一个方法,寻求播放的开始(playAtTime :),但我找不到一个直接的方式来指定声音文件结束之前的结束时间。

有没有办法做到这一点?

如果你不需要太高的精度,你想坚持使用AVAudioPlayer ,这是一个select:

 - (void)playAtTime:(NSTimeInterval)time withDuration:(NSTimeInterval)duration { NSTimeInterval shortStartDelay = 0.01; NSTimeInterval now = player.deviceCurrentTime; [self.audioPlayer playAtTime:now + shortStartDelay]; self.stopTimer = [NSTimer scheduledTimerWithTimeInterval:shortStartDelay + duration target:self selector:@selector(stopPlaying:) userInfo:nil repeats:NO]; } - (void)stopPlaying:(NSTimer *)theTimer { [self.audioPlayer pause]; } 

请记住, stopTimer会在线程的运行循环中触发,所以audio播放时间会有一些变化,具体取决于当时应用程序在做什么。 如果您需要更高级别的精度,请考虑使用AVPlayer而不是AVAudioPlayerAVPlayer播放AVPlayerItem对象,它允许您指定forwardPlaybackEndTime