如何在iOS上使用AVAudioPlayer播放指定持续时间的声音?
问题描述:
我想在IOS的声音文件中播放指定的时间。我在AVAudioPlayer中找到了一个寻找播放开始的方法(playAtTime :),但我找不到在声音文件结束之前指定结束时间的直接方法。如何在iOS上使用AVAudioPlayer播放指定持续时间的声音?
是否有办法实现这一点?
答
如果您并不需要太多的精度和你想坚持AVAudioPlayer
,这是一个选项:
- (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
将触发对线程的运行循环,所以会有一些音频播放时间的多变性,取决于当时该应用正在做什么。如果您需要更高级别的精度,请考虑使用AVPlayer
而不是AVAudioPlayer
。 AVPlayer
播放AVPlayerItem
对象,它允许您指定forwardPlaybackEndTime
。
感谢AVPlayer。我以前不知道。 –