Skip to content

Instantly share code, notes, and snippets.

@anzfactory
Last active August 29, 2015 14:04
Show Gist options
  • Save anzfactory/bec288d423ecbd612668 to your computer and use it in GitHub Desktop.
Save anzfactory/bec288d423ecbd612668 to your computer and use it in GitHub Desktop.
動画を指定位置で画像にして切り出す
// フレームワークを2つインポート
// <AssetsLibrary/AssetsLibrary.h> -> AssetLibrary.framework
// <AVFoundation/AVFoundation.h> -> AVFoundation.framework
+ (NSArray *)sliceMovie:(NSURL *)url
{
AVURLAsset* asset = [[AVURLAsset alloc] initWithURL:url options:nil];
if ( ! [asset tracksWithMediaCharacteristic:AVMediaTypeVideo]) {
NSLog(@"MovieUtil : ビデオタイプのファイルを指定して下さい [%@]", url);
return nil;
}
AVAssetImageGenerator *imageGen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
[imageGen setAppliesPreferredTrackTransform:YES];
// 動画から一定間隔毎に画像として切り出す
// 動画再生時間
NSMutableArray *images = [NSMutableArray new];
Float64 durationSeconds = CMTimeGetSeconds([asset duration]); // 動画の再生時間
Float64 interval = durationSeconds / 10; // 切り出す枚数
Float64 step = 0.f;
CMTime midpoint; // 切り出す位置
CMTime actualTime;
NSError *error = nil;
CGImageRef imageRef;
while (step < durationSeconds) {
// 切り出し箇所の指定
midpoint = CMTimeMakeWithSeconds(step, 30);
// 切り出し
imageRef = [imageGen copyCGImageAtTime:midpoint actualTime:&actualTime error:&error];
// エラー有無
if (error != nil) {
// とりあえず続けてみる
NSLog(@"MovieUtil : error [%@]", url);
error = nil;
continue;
}
// 切り出したものを保持
[images addObject:[[UIImage alloc] initWithCGImage:imageRef]];
// 解放
CGImageRelease(imageRef);
// つぎのぽいんとへ
step += interval;
}
return images;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment