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

Bas*_*awy 3 iphone audio playing avaudioplayer ios

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

有没有办法实现这个目标?

cdu*_*uhn 10

如果您不需要太多精确度并且想坚持下去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];
}
Run Code Online (Sandbox Code Playgroud)

请记住,这stopTimer将触发线程的运行循环,因此音频播放的时间会有一些变化,具体取决于应用程序当时正在做什么.如果您需要更高的精度,请考虑使用AVPlayer而不是AVAudioPlayer. AVPlayer播放AVPlayerItem对象,让你指定一个forwardPlaybackEndTime.