Я не могу получить точный CMtime для создания неподвижного изображения из 1,8 секунды видео
-
26-10-2019 - |
Вопрос
Каждый раз, когда я пытаюсь генерировать неподвижный кадр из своего видеосесси, он генерируется за время 0,000. Секунды. Я вижу это из моего сообщения журнала. Хорошо, что я могу получить изображение в момент времени 0,000 .. чтобы появиться в Uiimageview под названием «Myimageview». Я подумал, что проблема заключалась в том, что avurlassetpreferprecisionedurationAnturationAndtimingKey не был установлен, но даже после того, как я выяснил, как это сделать, он все еще не функционирует.
Вот что у меня есть ..
Время, фактическое время и генерация объявляются в заголовке
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/videoTest4.m4v"]];
//UISaveVideoAtPathToSavedPhotosAlbum(path, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
NSURL *url = [NSURL fileURLWithPath:path];
NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:url options:options];
Float64 durationSeconds = CMTimeGetSeconds([asset duration]);
generate = [[AVAssetImageGenerator alloc] initWithAsset:asset];
NSError *err = nil;
time = CMTimeMake(600,600.0);
CGImageRef imgRef = [generate copyCGImageAtTime:time actualTime:&actualTime error:&err];
UIImage *currentImg = [[UIImage alloc] initWithCGImage:imgRef];
myImageView.image = currentImg;
NSLog(@"The total Video Duration is %f",durationSeconds);
NSLog(@"The time I want my image is %f",CMTimeGetSeconds(time));
NSLog(@"The actual time my image was take was %f",CMTimeGetSeconds(actualTime));
И моя консоль читает ..
2011-04-28 18: 49: 59.062 Видеоализация [26553: 207] Общая продолжительность видео составляет 1,880000
2011-04-28 18: 49: 59.064 Видеоализация [26553: 207] Время, которое я хочу, мое изображение-1.000000
2011-04-28 18: 49: 59.064 Видеоализация [26553: 207] Фактическое время, когда мое изображение было 0,000000
..........................
Спасибо, ребята, заранее .. :)
Решение
Чтобы решить это, вам просто нужно установить Запрашивался а также Запрашивается, что в KCMTimezero для avassetimagegenerator.
Другие советы
Поздно прошлой ночью у меня была идея, и, конечно же, это сработало сегодня утром. По сути, я просто создаю новый композиционный актив, а затем создаю диапазон времени, который представляет одну кадр для видео с 24 кадрами в секунду. Как только у меня созданы эти композиции, я просто получаю первый кадр каждого комплекса. Я делаю это для каждого кадра и создаю массив, держащий все мои рамки. Вот что я сделал ..
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/videoTest4.m4v"]];
//UISaveVideoAtPathToSavedPhotosAlbum(path, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
NSURL *url = [NSURL fileURLWithPath:path];
NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:url options:options];
Float64 durationFrames = CMTimeGetSeconds([asset duration]) * 24.0;
AVMutableComposition *myComp = [AVMutableComposition composition];
AVMutableCompositionTrack *compositionVideoTrack = [myComp addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
NSError *error = nil;
BOOL ok = NO;
NSMutableArray* frameArray = [[NSMutableArray alloc] init];
generate = [[AVAssetImageGenerator alloc] initWithAsset:myComp];
NSError *err = nil;
for (int i = 0; i < floor(durationFrames); i++) {
CMTime startTime = CMTimeMake(i, 24);
CMTime endTime = CMTimeMake(i+1, 24);
CMTimeRange myRange = CMTimeRangeMake(startTime, endTime);
AVAssetTrack *sourceVideoTrack = [[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];
ok = [compositionVideoTrack insertTimeRange:myRange ofTrack:sourceVideoTrack atTime:kCMTimeZero error:&error];
if (!ok) {
// Deal with the error.
}
time = CMTimeMake(0,1);
CGImageRef imgRef = [generate copyCGImageAtTime:time actualTime:&actualTime error:&err];
UIImage *currentImg = [[UIImage alloc] initWithCGImage:imgRef];
[frameArray addObject:currentImg];
[currentImg release];
}
NSLog(@"This video is calculated at %f Frames..",durationFrames);
NSLog(@"You made a total of %i Frames!!",[frameArray count]);
Тогда консоль читается ..
2011-04-29 10: 42: 24.292 Видеоализация [29019: 207] Это видео рассчитано на 45,120000 кадров ..
2011-04-29 10: 42: 24.293 Видеоализация [29019: 207] Вы сделали в общей сложности 45 кадров !!