我正在尝试使用 AVMutableComposition 在精确的时间播放一系列声音文件。
当视图加载时,我创建的目的是在 1 秒内均匀地播放 4 个声音。声音的长短无关紧要,我只想在 0、0.25、0.5 和 0.75 秒时触发它们:
AVMutableComposition *composition = [[AVMutableComposition alloc] init];
NSDictionary *options = @{AVURLAssetPreferPreciseDurationAndTimingKey : @YES};
for (NSInteger i = 0; i < 4; i++)
{
AVMutableCompositionTrack* track = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
NSURL *url = [[NSBundle mainBundle] URLForResource:[NSString stringWithFormat:@"sound_file_%i", i] withExtension:@"caf"];
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:url options:options];
AVAssetTrack *assetTrack = [asset tracksWithMediaType:AVMediaTypeAudio].firstObject;
CMTimeRange timeRange = [assetTrack timeRange];
Float64 t = i * 0.25;
NSError *error;
BOOL success = [track insertTimeRange:timeRange ofTrack:assetTrack atTime:CMTimeMakeWithSeconds(t, 1) error:&error];
if (!success)
{
NSLog(@"unsuccesful creation of composition");
}
if (error)
{
NSLog(@"composition creation error: %@", error);
}
}
AVPlayerItem* playerItem = [AVPlayerItem playerItemWithAsset:composition];
self.avPlayer = [[AVPlayer alloc] initWithPlayerItem:playerItem];
合成成功创建,没有错误。后来,当我想播放序列时,我这样做:
[self.avPlayer seekToTime:CMTimeMakeWithSeconds(0, 1)];
[self.avPlayer play];
出于某种原因,这些声音根本不是均匀分布的——而是几乎同时播放所有声音。我尝试了同样的事情,间隔超过 4 秒,替换了这样的时间计算:
Float64 t = i * 1.0;
这玩得很完美。任何低于 1 秒的时间间隔似乎都会产生意想不到的结果。我错过了什么?AVCompositions 不应该用于 1 秒以下的时间间隔吗?还是我误解了时间间隔?