如果想要减少 AVCaptureVideoDataOutput 消耗的内存,可以使用 AVCaptureMovieFileOutput 来替代。代码示例如下:
AVCaptureSession *captureSession = [[AVCaptureSession alloc] init];
AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
AVCaptureDeviceInput *videoInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:nil];
if (videoInput) {
[captureSession addInput:videoInput];
}
AVCaptureMovieFileOutput *movieOutput = [[AVCaptureMovieFileOutput alloc] init];
if ([captureSession canAddOutput:movieOutput]) {
[captureSession addOutput:movieOutput];
}
[captureSession startRunning];
NSURL *outputURL = //设置输出文件路径
NSString *audio = [[NSBundle mainBundle] pathForResource:@"example" ofType:@"m4a"];
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:audio] options:nil];
AVMutableComposition *composition = [[AVMutableComposition alloc] init];
AVMutableCompositionTrack *audioTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
AVAssetTrack *assetTrack = [asset tracksWithMediaType:AVMediaTypeAudio][0];
NSError *error = nil;
BOOL ok = [audioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, asset.duration)
ofTrack:assetTrack
atTime:kCMTimeZero
error:&error];
if (!ok) {
// Handle the error.
}
AVMutableVideoCompositionInstruction *instruction = [[AVMutableVideoCompositionInstruction alloc] init];
instruction.timeRange = CMTimeRangeMake(kCMTimeZero, composition.duration);
AVMutableVideoCompositionLayerInstruction *layerInstruction = [[AVMutableVideoCompositionLayerInstruction alloc] init];
[layerInstruction setTransform:videoTrack.preferredTransform atTime:kCMTimeZero];
instruction.layerInstructions = @[layerInstruction];
AVMutableVideoComposition *videoComposition = [[AVMutableVideoComposition alloc] init];
videoComposition.instructions = @[instruction];
videoComposition.frameDuration = CMTimeMake(1, 30);
videoComposition.renderSize = CGSizeMake(1280, 720);
NSError *exportError = nil;
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPreset1280x720];
exportSession.outputURL = outputURL;
exportSession.outputFileType = AVFileTypeMPEG4;
exportSession.videoComposition = videoComposition;
exportSession.shouldOptimizeForNetworkUse = YES;
[exportSession exportAsynchronouslyWithCompletionHandler:^{
if (exportSession.status == AVAssetExportSession