3

我想在 IOS 的声音文件中播放指定的持续时间。我在 AVAudioPlayer 中找到了一种方法,它试图开始播放(playAtTime:),但我找不到在声音文件结束之前指定结束时间的直接方法。

有没有办法做到这一点?

4

1 回答 1

12

If you don't need much precision and you want to stick with AVAudioPlayer, this is one option:

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

Bear in mind that stopTimer will fire on the thread's run loop, so there will be some variability in how long the audio plays, depending on what else the app is doing at the time. If you need a higher level of precision, consider using AVPlayer instead of AVAudioPlayer. AVPlayer plays AVPlayerItem objects, which let you specify a forwardPlaybackEndTime.

于 2011-07-05T03:47:07.400 回答