0

我有服务器应用程序,它提供有关服务器上视频的信息。其中一个请求是 URL:PORT/video/:id/:time ... 我解析并获取视频文件,准备时间并询问生成缩略图的方法。它在前 5 分钟内运行得非常快(在 200 毫秒内生成图像),然后图像生成过程突然​​需要 10 秒......

你知道为什么吗?使用的代码:

-(NSImage *)thumbnailAt: (CMTime)        time
               withSize: (NSSize)        size
                  error: (NSError **)    error {

    @autoreleasepool {
         if ( self.assetChanged ) {
             self.generate = [[AVAssetImageGenerator alloc] initWithAsset:_asset];
             self.generate.appliesPreferredTrackTransform = TRUE;
             self.assetChanged = NO;
         }

         self.generate.maximumSize = NSSizeToCGSize(size);

         CGImageRef imageReference = [self.generate copyCGImageAtTime:time actualTime:NULL error:error];

        if ( imageReference != nil ) {
            NSImage* ret = [[NSImage alloc] initWithCGImage:imageReference size:size];
            CGImageRelease(imageReference);
            return ret;
        }

        return nil;
    }
}

知道我做错了什么或任何建议如何以不同的方式做(例如使用 AVAssetReader)?

4

1 回答 1

0

最后我用不同的方法解决了这个问题:我使用了异步图像

-(NSImage *)createAsyncThumbnailAtTime:(CMTime)time withSize:(NSSize)size {
    if ( self.updated ) {
        [_generator cancelAllCGImageGeneration]; // Stop we did not comply in time.
        _generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:_asset];
        _generator.maximumSize = NSSizeToCGSize(size);
    }

    NSMutableArray * times = [NSMutableArray array];
    [times addObject:[NSValue valueWithCMTime:time]];

    __block NSImage * image;
    __block BOOL finished = NO;

    [_generator generateCGImagesAsynchronouslyForTimes:times completionHandler:^(CMTime requestedTime, CGImageRef imageRef, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error) {

        image = nil;

        if ( result == AVAssetImageGeneratorCancelled ) {
            image = nil;
            NSLog(@"CANCELLED %@", error);
            finished = YES;
        }
        else
            if ( result == AVAssetImageGeneratorFailed ) {
                image   = nil;
                NSLog(@"FAILDED %@", error);
                finished = YES;
            }
            else /* result == AVAssetImageGeneratorSucessed */
            {
                image = [[NSImage alloc] initWithCGImage:imageRef size:size];
                finished = YES;
            }
    }];

    while ( !finished ) {
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    }

    return thumbnail->image;
}
于 2015-03-19T12:11:36.287 回答