tracksWithMediaType returns 0 tracks sometimes

2019-07-18 23:54发布

In my app I combine several .m4a audio files. For combining audio files I use below code.

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);
}

Sometimes 'tracksWithMediaType' returns empty array. Why is this happening and any help would be greatly appreciated.

1条回答
贼婆χ
2楼-- · 2019-07-19 00:10

When you create AVAsset with:

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

asset must have loaded its tracks before ready for use:

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

 }
}];
查看更多
登录 后发表回答