将视频保存到DocumentsDirectory

时间:2017-11-27 08:45:51

标签: ios objective-c xcode

我正在尝试使用编码目标c来改善自我,我不能很好地解决这个问题。 我使用下面的代码将视频与音频合并,并将最终视频保存到相机胶卷。代码工作正常,但我需要的是将该视频保存到临时文档中,这样我就可以更改或修改视频而不会在每次进行小的更改时保存它。

这是我的代码:

from django.conf.urls import url
from . import views


urlpatterns = [
url(r'^auth/$', views.authenticate_for_token, name='authenticate'),

url(r'^records/all/(?P<token>[1-9]_[a-z]*)/$', views.records_list_all, name='records_all'),
url(r'^records/(?P<offset>[0-9]*)/(?P<limit>[1-9][0-9]*)/(?P<token>[1-9]_[a-z]*)/(?P<comp_code>[0-9]{2,8})/$', views.records_list_subset, name='records_all'),
url(r'^records/save/$', views.records_save, name='records_save'),

url(r'^dropdown/(?P<comp_code>[0-9]{2,8})/(?P<token>[1-9]_[a-z]*)/$', views.get_dropdown_lists, name='dropdown_lists'),

url(r'^approve/$', views.approve_category, name='approve_category'),
url(r'^approve/delete/$', views.approve_category_delete, name='approve_category_delete'),

url(r'^hide-sheet/$', views.hide_sheet, name='hide_sheet'),
url(r'^hide-sheet/delete/$', views.hide_sheet_delete, name='hide_sheet_delete'),


url(r'^template/download/$', views.template_download, name='template_download'),
url(r'^template/upload/$', views.template_upload, name='template_upload'),

url(r'^overview/$', views.Overview.as_view(), name='admin_overview'),

url(r'^login/$', views.LoginView.as_view(), name='login'),
url(r'^logout/$', views.logout_func, name='logout'),
url(r'^user/$', views.UserManagement.as_view(), name='user_mgmt'),
url(r'^user/upsert/$', views.user_create, name='user_create'),

url(r'^debug/$', views.debug_func, name='debug'),

]

她是我将视频导出到相机胶卷的地方:

- (IBAction)addBackgroundMusicAction:(UIButton *)sender {
    if (self.asset == nil) {
        return;
    }


    NSString *outPutPath = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"mergeVideo-%d.mov",arc4random() % 1000]];

    NSURL *outPutUrl = [NSURL fileURLWithPath:outPutPath];
    if ([[NSFileManager defaultManager] fileExistsAtPath:outPutPath])
    {
        [[NSFileManager defaultManager] removeItemAtPath:outPutPath error:nil];
    }
    AVMutableComposition *composition = [AVMutableComposition composition];
    CMTimeRange videoTimeRange = CMTimeRangeMake(kCMTimeZero, self.asset.duration);
    AVMutableCompositionTrack *videoTrack = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];

    AVAssetTrack *videoAssetTrack = [[self.asset tracksWithMediaType:AVMediaTypeVideo] firstObject];
    [videoTrack insertTimeRange:videoTimeRange ofTrack:videoAssetTrack atTime:kCMTimeZero error:nil];

    AVURLAsset *audioAsset = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"myAudio" ofType:@"mp3"]] options:nil];
    AVMutableCompositionTrack *audioTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
    AVAssetTrack *audioAssetTrack = [[audioAsset tracksWithMediaType:AVMediaTypeAudio] firstObject];
    [audioTrack insertTimeRange:videoTimeRange ofTrack:audioAssetTrack atTime:kCMTimeZero error:nil];


    // 3.1 - Create AVMutableVideoCompositionInstruction
    AVMutableVideoCompositionInstruction *mainInstruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
    mainInstruction.timeRange = CMTimeRangeMake(kCMTimeZero, self.asset.duration);
    // 3.2 - Create an AVMutableVideoCompositionLayerInstruction for the video track and fix the orientation.
    AVMutableVideoCompositionLayerInstruction *videolayerInstruction = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:videoTrack];
    UIImageOrientation videoAssetOrientation_  = UIImageOrientationUp;
    BOOL isVideoAssetPortrait_  = NO;
    CGAffineTransform videoTransform = videoAssetTrack.preferredTransform;
    if (videoTransform.a == 0 && videoTransform.b == 1.0 && videoTransform.c == -1.0 && videoTransform.d == 0) {
        videoAssetOrientation_ = UIImageOrientationRight;
        isVideoAssetPortrait_ = YES;
    }
    if (videoTransform.a == 0 && videoTransform.b == -1.0 && videoTransform.c == 1.0 && videoTransform.d == 0) {
        videoAssetOrientation_ =  UIImageOrientationLeft;
        isVideoAssetPortrait_ = YES;
    }
    if (videoTransform.a == 1.0 && videoTransform.b == 0 && videoTransform.c == 0 && videoTransform.d == 1.0) {
        videoAssetOrientation_ =  UIImageOrientationUp;
    }
    if (videoTransform.a == -1.0 && videoTransform.b == 0 && videoTransform.c == 0 && videoTransform.d == -1.0) {
        videoAssetOrientation_ = UIImageOrientationDown;
    }
    [videolayerInstruction setTransform:videoAssetTrack.preferredTransform atTime:kCMTimeZero];
    [videolayerInstruction setOpacity:0.0 atTime:self.asset.duration];

    // 3.3 - Add instructions
    mainInstruction.layerInstructions = [NSArray arrayWithObjects:videolayerInstruction,nil];

    AVMutableVideoComposition *mainCompositionInst = [AVMutableVideoComposition videoComposition];

    CGSize naturalSize;
    if(isVideoAssetPortrait_){
        naturalSize = CGSizeMake(videoAssetTrack.naturalSize.height, videoAssetTrack.naturalSize.width);
    } else {
        naturalSize = videoAssetTrack.naturalSize;
    }

    float renderWidth, renderHeight;
    renderWidth = naturalSize.width;
    renderHeight = naturalSize.height;
    mainCompositionInst.renderSize = CGSizeMake(renderWidth, renderHeight);
    mainCompositionInst.instructions = [NSArray arrayWithObject:mainInstruction];
    mainCompositionInst.frameDuration = CMTimeMake(1, 30);


    AVAssetExportSession * assetExport = [[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPresetMediumQuality];
    assetExport.outputURL = outPutUrl;
    assetExport.outputFileType = AVFileTypeQuickTimeMovie;
    assetExport.shouldOptimizeForNetworkUse = YES;
    assetExport.videoComposition = mainCompositionInst;
    [assetExport exportAsynchronouslyWithCompletionHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [self exportDidFinish:assetExport];
        });
    }];
}

正如我所说,我不需要将视频保存到相机胶卷,我只需要将其保存为临时。另外,当我按下另一个按钮时,我需要加载该视频。保存该视频并重新加载。

由于

1 个答案:

答案 0 :(得分:1)

使用以下代码:

 NSData *videoData = [NSData dataWithContentsOfURL:outputURL];
    if (videoData) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"MyFolder"];
        // Create folder if needed
        [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:YES attributes:nil error:nil];

        NSString *filePath = [dataPath stringByAppendingPathComponent:@"test.mp4"];
        if ([videoData writeToFile:filePath atomically:YES]) {
            // yeah - file written
        } else {
            // oops - file not written
        }
    } else {
        // oops - couldn't get data
    }