我正在尝试使用AVMutableComposition在精确的时间播放一系列音频文件。
当视图加载时,我创建了一个组合,以便在1秒内平均播放4个声音。声音的长度不重要,我只想在0秒、0.25秒、0.5秒和0.75秒准确地触发它们。
当视图加载时,我创建了一个组合,以便在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秒的时间间隔似乎都会产生意想不到的结果。我错过了什么吗?AVComposition不应该用于小于1秒的时间间隔吗?或者我可能误解了时间间隔的含义?