iOS: AVPlayerItem в AVAsset

У меня есть 2 AVAssets, и у меня есть изменения с помощью VideoComposition и AudioMix для AVPlayerItem. После этого я использую ассет из AVPlayerItem, но VideoComposition и AudioMix не применяются. Я хочу, чтобы результирующий ресурс применялся как VideoComposition, так и AudioMix. Вот код.

+ (AVAsset *)InitAsset:(AVAsset *)asset AtTime:(double)start ToTime:(double)end {
CGFloat colorComponents[4] = {1.0,1.0,1.0,0.0};

//Create AVMutableComposition Object.This object will hold our multiple AVMutableCompositionTrack.
AVMutableComposition* mixComposition = [[AVMutableComposition alloc] init];

//Here we are creating the first AVMutableCompositionTrack.See how we are adding a new track to our AVMutableComposition.
AVMutableCompositionTrack *masterTrack =
[mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo
                            preferredTrackID:kCMPersistentTrackID_Invalid];
//Now we set the length of the firstTrack equal to the length of the firstAsset and add the firstAsset to out newly created track at kCMTimeZero so video plays from the start of the track.
[masterTrack insertTimeRange:CMTimeRangeMake(CMTimeMakeWithSeconds(start, 1), CMTimeMakeWithSeconds(end, 1))
                     ofTrack:[[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0]
                      atTime:kCMTimeZero error:nil];

// Each video layer instruction
AVMutableVideoCompositionLayerInstruction *masterLayerInstruction = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:masterTrack];
[masterLayerInstruction setOpacity:1.0f atTime:kCMTimeZero];
[masterLayerInstruction setOpacityRampFromStartOpacity:1.0f
                                          toEndOpacity:0.0
                                             timeRange:CMTimeRangeMake(CMTimeMakeWithSeconds(end, 1), CMTimeMakeWithSeconds(end + ANIMATION_FADE_TIME, 1))];

//See how we are creating AVMutableVideoCompositionInstruction object.This object will contain the array of our AVMutableVideoCompositionLayerInstruction objects.You set the duration of the layer.You should add the lenght equal to the lingth of the longer asset in terms of duration.
AVMutableVideoCompositionInstruction * MainInstruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
[MainInstruction setTimeRange:CMTimeRangeMake(kCMTimeZero, CMTimeMakeWithSeconds(end + ANIMATION_FADE_TIME, 1))];
[MainInstruction setLayerInstructions:[NSArray arrayWithObjects:masterLayerInstruction,nil]];
[MainInstruction setBackgroundColor:CGColorCreate(CGColorSpaceCreateDeviceRGB(), colorComponents)];

//Now we create AVMutableVideoComposition object.We can add mutiple AVMutableVideoCompositionInstruction to this object.We have only one AVMutableVideoCompositionInstruction object in our example.You can use multiple AVMutableVideoCompositionInstruction objects to add multiple layers of effects such as fade and transition but make sure that time ranges of the AVMutableVideoCompositionInstruction objects dont overlap.
AVMutableVideoComposition *MainCompositionInst = [AVMutableVideoComposition videoComposition];
MainCompositionInst.instructions = [NSArray arrayWithObject:MainInstruction];
MainCompositionInst.frameDuration = CMTimeMake(1, 30);
MainCompositionInst.renderSize = CGSizeMake(1280, 720);
//    [MainCompositionInst setFra]

AVMutableCompositionTrack *masterAudio = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
[masterAudio insertTimeRange:CMTimeRangeMake(kCMTimeZero, CMTimeMakeWithSeconds(end + ANIMATION_FADE_TIME, 1))
                     ofTrack:[[asset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0] atTime:kCMTimeZero error:nil];

// Each Audio
AVMutableAudioMixInputParameters *masterAudioMix = [AVMutableAudioMixInputParameters audioMixInputParametersWithTrack:masterAudio];
[masterAudioMix setVolume:1.0f atTime:kCMTimeZero];
[masterAudioMix setVolumeRampFromStartVolume:1.0f
                                 toEndVolume:0.0f
                                   timeRange:CMTimeRangeMake(CMTimeMakeWithSeconds(end, 1), CMTimeMakeWithSeconds(end + ANIMATION_FADE_TIME, 1))];
//    [SecondTrackMix setVolume:1.0f atTime:CMTimeMake(2.01, 1)];

AVMutableAudioMix *audioMix = [AVMutableAudioMix audioMix];
audioMix.inputParameters = [NSArray arrayWithObjects:masterAudioMix,nil];

//Finally just add the newly created AVMutableComposition with multiple tracks to an AVPlayerItem and play it using AVPlayer.
AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:mixComposition];
item.videoComposition = MainCompositionInst;
item.audioMix = audioMix;

return [item asset];
}

У кого-нибудь есть идеи?

С уважением.


person Chanin Pakdeethammasakul    schedule 23.04.2014    source источник
comment
Я не понимаю этот вопрос. Вы хотите что-то изменить, или вы что-то изменили, но не применили? Не могли бы вы отредактировать свой вопрос, чтобы показать код того, что вы пытаетесь сделать?   -  person Michael Dautermann    schedule 24.04.2014
comment
Спасибо за ответ. Я уже отредактировал.   -  person Chanin Pakdeethammasakul    schedule 24.04.2014


Ответы (1)


Используйте AVAssetExportSeesion...

«Объект AVAssetExportSession перекодирует содержимое исходного объекта AVAsset для создания вывода в форме, описанной заданным предустановленным параметром экспорта».

Используйте свойства audioMix и videoComposition в AVAssetExportSeesion.


audioMix Указывает, включено ли для экспорта микширование звука не по умолчанию, и предоставляет параметры для микширования звука.

@property(nonatomic, copy) AVAudioMix *audioMix


videoComposition Указывает, включена ли композиция видео для экспорта, и предоставляет инструкции для композиции видео.

@property(nonatomic, copy) AVVideoComposition *videoComposition

person Roecrew    schedule 24.04.2014
comment
Могу ли я экспортировать их в AVAsset вместо файла? - person Chanin Pakdeethammasakul; 24.04.2014
comment
Не с AVAssetExportSession. Почему бы просто не использовать метод AVAsset + (id)assetWithURL:(NSURL *)URL? - person Roecrew; 24.04.2014
comment
Потому что мне нужно повторить этот метод, и экспорт в файл перед повторным открытием занимает много времени. - person Chanin Pakdeethammasakul; 24.04.2014