简体   繁体   English

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

[英]How can you play a sound of a specified duration using AVAudioPlayer on iOS?

I want to play a specified duration within a sound file on IOS.我想在 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.我在 AVAudioPlayer 中找到了一种方法,该方法试图开始播放 (playAtTime:),但我找不到在声音文件结束之前指定结束时间的直接方法。

Is there is a way to achieve this?有没有办法做到这一点?

If you don't need much precision and you want to stick with AVAudioPlayer , this is one option:如果您不需要太多精度并且想坚持使用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];
}

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.请记住, stopTimer将在线程的运行循环上触发,因此音频播放时长会有一些变化,具体取决于应用程序当时正在执行的其他操作。 If you need a higher level of precision, consider using AVPlayer instead of AVAudioPlayer .如果您需要更高级别的精度,请考虑使用AVPlayer而不是AVAudioPlayer AVPlayer plays AVPlayerItem objects, which let you specify a forwardPlaybackEndTime . AVPlayer播放AVPlayerItem对象,可让您指定forwardPlaybackEndTime

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM