QTKit - 合并两个不同宽度和高度的视频?
Posted
技术标签:
【中文标题】QTKit - 合并两个不同宽度和高度的视频?【英文标题】:QTKit - Merge two videos with different width and height? 【发布时间】:2012-02-09 14:53:38 【问题描述】:我刚刚做了一个简单的应用,它使用 QTKit 将两个视频合并在一起
这是问题:
我刚刚发现,如果我尝试合并两个具有不同宽度和高度的视频,输出是一个视频,其高度和宽度与大视频相同,但包含带有黑色和宽边框的小视频。
问题:
如何将两个视频合并在一起并获得格式正确(宽度/高度)的输出视频?
更好地理解我需要的示例:
我有两个视频:
视频 1 = 1920 x 1280 视频 2 = 1280 x 960
我想要什么:1920 x 1280 的视频(需要放大并裁剪小的视频)
代码:
-(void)voidMethodToCombine
NSError *err = nil;
QTMovie *myCombinedMovie = [[QTMovie alloc] initToWritableData:[NSMutableData data] error:&err];
if (err)
NSRunAlertPanel(@"Errore nella creazione del video",[err localizedDescription], nil, @"Chiudi", nil, nil);
return;
return;
// Create the File Open Dialog class.
NSSavePanel *savePanel = [NSSavePanel savePanel]; //Dove salvo il video ?
if ([savePanel runModal])//Se premo ok
[indicatore setUsesThreadedAnimation:YES];
[indicatore startAnimation:self];
NSURL *saveURL = savePanel.URL;
NSString *savePath = [saveURL path];
//Prelevo i 2 percorsi e gli inserisco negli array
NSString *video1 = [URLVideo1 stringValue];
NSString *video2 = [URLVideo2 stringValue];
NSURL *theURLvideo1 = [NSURL fileURLWithPath:video1];
NSURL *theURLvideo2 = [NSURL fileURLWithPath:video2];
if((theURLvideo1) && (theURLvideo2))
NSArray *myMovieURLs = [NSArray arrayWithObjects:theURLvideo1,theURLvideo2, nil];
for (NSURL *url in myMovieURLs)
QTMovie *theMovie = [QTMovie movieWithURL:url error:&err];
if (err)
NSRunAlertPanel(@"Errore durante il caricamento di uno dei film",[err localizedDescription], nil, @"Chiudi", nil, nil);
return;
QTTimeRange timeRange = QTMakeTimeRange(QTZeroTime, [theMovie duration]);
QTTime insertionTime = [myCombinedMovie duration];
[myCombinedMovie insertSegmentOfMovie:theMovie timeRange:timeRange atTime:insertionTime];
NSDictionary *writeAttributes = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], QTMovieFlatten, nil];
//Pannello di path salvataggio
bool success = [myCombinedMovie writeToFile:savePath withAttributes:writeAttributes error:&err];
[indicatore stopAnimation:self];
NSBeep();
NSString *dove = [[NSString alloc] initWithFormat:@"Video esportato in:\n%@",savePath];
NSRunAlertPanel(@"Esportazione avvenuta con successo!", dove, @"Ok", nil, nil);
if (!success)
NSRunAlertPanel(@"Errore durante il salvataggio del video.",[err localizedDescription], nil, @"Chiudi", nil, nil);
return;
return;
//Se non esiste alcun percorso
else
NSRunAlertPanel(@"Impossibile selezionare i file.", @"Controlla di aver specificato un percorso.", @"Chiudi", nil, nil);
【问题讨论】:
【参考方案1】:要做到这一点,最简单的方法是使用 AVFoundation 框架而不是 QTKit,因为编辑/操作视频要容易得多 (imo),尽管它似乎有点慢并且代码可能不太紧凑。
我建议先阅读https://developer.apple.com/library/mac/documentation/AudioVideo/Conceptual/AVFoundationPG/AVFoundationPG.pdf 的 AVFoundation 编程指南
但这里有一个基本示例可以帮助您入门。在开始之前,请确保您已链接到 AVFoundation 和 CoreMedia 框架。
在您的标题中,除了您可能添加的任何其他方法或 ivars 之外,您还可以添加 AVAssetExportSession *exporter
和 NSTimer *timer
,以及方法 - (void) monitorProgress;
。
然后,您的实现文件将包含以下方法(假设您使用名为 doIt 的 IBAction 触发该方法)。别忘了#import <AVFoundation/ AVFoundation.h>
和#import <CoreMedia/CoreMedia.h>
:
- (IBAction)doIt:(id)sender
// Initial array of movie URLs
NSArray *myMovieURLs = [NSArray arrayWithObjects:[NSURL fileURLWithPath:@"/path/to/first.mov"], [NSURL fileURLWithPath:@"/path/to/second.mov"], nil];
// Create the composition & A/V tracks
AVMutableComposition *comp = [AVMutableComposition composition];
AVMutableCompositionTrack *compositionVideoTrack = [comp addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
AVMutableCompositionTrack *compositionAudioTrack = [comp addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
// A reference for insertion start time
CMTime startTime = kCMTimeZero;
for (int i=0; i< [myMovieURLs count]; i++)
// Get asset
NSURL *movieURL = [myMovieURLs objectAtIndex:i];
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:movieURL options:nil];
// Get video and audio tracks (assuming video exists - test for audio as an empty track will crash the program!) and insert in composition tracks
AVAssetTrack *videoTrack = [[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];
bool success = [compositionVideoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, [asset duration]) ofTrack:videoTrack atTime:startTime error:nil];
if ([[asset tracksWithMediaType:AVMediaTypeAudio]count])
AVAssetTrack *audioTrack = [[asset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0];
success = [compositionAudioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, [asset duration]) ofTrack:audioTrack atTime:startTime error:nil];
// increment the start time to the end of this first video
startTime = CMTimeAdd(startTime, [asset duration]);
//Set the output URL
NSURL *outputURL = [NSURL fileURLWithPath:@"/path/to/output.mov"];
/* Create the exporter.
Note the preset type is up to you to choose. If you wanted, you could check the asset's size (with [asset naturalSize]) or other values above and use that to base your preset on.
Use exportPresetsCompatibleWithAsset: to get a list of presets that are compatible with a specific asset.
*/
NSLog(@"Compat presets you could use: %@", [AVAssetExportSession exportPresetsCompatibleWithAsset:comp]);
exporter = [[AVAssetExportSession alloc] initWithAsset:comp presetName:AVAssetExportPreset640x480];
[exporter setOutputURL:outputURL];
[exporter setOutputFileType:AVFileTypeQuickTimeMovie];
[exporter exportAsynchronouslyWithCompletionHandler:^(void)
switch ([exporter status])
case AVAssetExportSessionStatusFailed:
NSLog(@"Export failed: %@", [[exporter error] localizedDescription]);
break;
case AVAssetExportSessionStatusCancelled:
NSLog(@"Export canceled");
break;
default:
break;
];
// This is just a simple timer that will call a method to log the progress
timer=[NSTimer scheduledTimerWithTimeInterval:5
target:self
selector:@selector(monitorProgress)
userInfo:nil
repeats:YES];
-(void)monitorProgress
if ([exporter progress] == 1.0)
[timer invalidate];
NSLog(@"Progress: %f",[exporter progress]* 100);
【讨论】:
好吧,我已经导入了 AVFramework 并在标题中声明了它。然后我编辑了我的代码,在我尝试构建之前没有给出任何错误。我做了一个screenshot。基本上,它是这样说的:** -[LDAppDelegate doIt:] in LDAppDelegate.o ld:未找到架构 x86_64 clang 的符号:错误:链接器命令失败,退出代码为 1(使用 -v 查看调用)**谢谢。 我做了两张截图让你更好理解:Header file -- Implementation file 您会在第一个屏幕截图(其中一个错误)中注意到,问题出在 kCMTimeZero、CMTimeRangeMake 等。它们来自 CoreMedia 框架。您需要添加 CoreMedia 框架并导入它。那应该可以解决编译问题。我将编辑我的答案以提及这一点,因为它最初让我忘记了。 谢谢你。最后一件事:你知道如何将具有不同选项的选择菜单添加到保存面板吗?有参考吗? 通常你会通过使用 NSSavePanel 的 setAccessoryView 添加自定义视图来实现。它包含在文件系统编程指南的“使用打开和保存面板”部分中,找到 here以上是关于QTKit - 合并两个不同宽度和高度的视频?的主要内容,如果未能解决你的问题,请参考以下文章