How can you play a sound of a specified duration u

2020-02-29 10:40发布

问题:

I want to play a specified duration within a sound file on IOS. I found a method in AVAudioPlayer that seeks to the begining of the playing (playAtTime:) but i cannot find a direct way to specify an end time before the end of the sound file.

Is there is a way to achieve this?

回答1:

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.