tracksWithMediaType有时会返回0个曲目

时间:2016-07-18 14:29:38

标签: ios objective-c iphone avaudiorecorder

在我的应用中,我合并了多个.m4a音频文件。对于组合音频文件,我使用下面的代码。

CMTime nextClipStartTime = kCMTimeZero;
AVMutableComposition *composition = [[AVMutableComposition alloc] init];
AVMutableCompositionTrack *compositionAudioTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];


for(NSString * str in filesNamesArray)
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:str];
    NSURL *url = [[NSURL alloc] initFileURLWithPath:path];

    AVAsset *avAsset = [[AVURLAsset alloc] initWithURL:url options:nil];

    NSArray *tracks = [avAsset tracksWithMediaType:AVMediaTypeAudio];
    if ([tracks count] == 0)
    {
        NSLog(@"Tracks = %lu",(unsigned long)[tracks count]);
        return;
    }
    NSLog(@"%@",avAsset);
    CMTimeRange timeRangeInAsset = CMTimeRangeMake(kCMTimeZero, [avAsset duration]);
    AVAssetTrack *clipAudioTrack = [[avAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0];
    ok = [compositionAudioTrack insertTimeRange:timeRangeInAsset  ofTrack:clipAudioTrack atTime:nextClipStartTime error:&error];
    if (!ok) {
        NSLog(@"Current Video Track Error: %@",error);
    }
    nextClipStartTime = CMTimeAdd(nextClipStartTime, timeRangeInAsset.duration);
}

有时' trackWithMediaType'返回空数组。为什么会发生这种情况,我们将非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

使用以下命令创建AVAsset时

AVAsset *avAsset = [[AVURLAsset alloc] initWithURL:url options:nil];

资产必须在准备好使用之前加载其轨道:

[avAsset loadValuesAsynchronouslyForKeys:@"tracks" completionHandler: ^{
 AVKeyValueStatus status = [avAsset statusOfValueForKey:@"tracks" error:nil];
 if (status == AVKeyValueStatusLoaded) { 
     // Asset is ready now

 }
}];