【问题标题】:Can videos recorded using AVFoundation be written directly to the Assets Library?使用 AVFoundation 录制的视频可以直接写入 Assets Library 吗?
【发布时间】:2012-10-07 07:27:32
【问题描述】:

我正在使用 AVFoundation 使用以下方法将视频录制到 NSTemporaryDirectory。

[[self movieFileOutput] startRecordingToOutputFileURL:[self outputFileURL] recordingDelegate:self];

录制停止后

[library writeVideoAtPathToSavedPhotosAlbum:outputFileURLcompletionBlock:^(NSURL *assetURL, NSError *error)`

方法被调用。

我注意到,当视频从临时目录写入照片库时,它会一直保留在那里,直到保存完成。

这对我来说没有意义,因为它在保存视频时需要双倍的磁盘空间。例如,如果我录制一小时长的 1080p 视频,在录制结束时磁盘大小为 5GB,但在删除临时文件并释放磁盘空间之前保存到照片库时会增加到 10GB。

很想听听您对此的看法。

【问题讨论】:

    标签: video avfoundation alassetslibrary


    【解决方案1】:

    我认为,最好将视频临时存储到 Document-directory 为 .mp4。

    然后保存到文档目录,保存后删除。

    NSString *videoPath = [[self getDirectoryPath:[NSString stringWithUTF8String:currentRequest.fileName]] retain];
    
     NSURL *videoPathURL = [NSURL URLWithString:videoPath];                 
    
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];  
    
    [library writeVideoAtPathToSavedPhotosAlbum:videoPathURL completionBlock:^(NSURL *assetURL, NSError *error) { 
    
           //Delete "videoPath" file from Document directory
    
    }]; 
    
    
    -(NSString *)getDirectoryPath:(NSString *)fileName {        
    
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    
        NSString *documentsDirectory = [paths objectAtIndex:0];
    
        NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp4",fileName]];
        return path;
    
    }
    

    【讨论】:

      【解决方案2】:

      录制时,您似乎无法将视频文件直接写入照片库。但是您可以将您在应用程序目录中写入的文件(如临时、文档等)移动到照片库,而不是复制文件。这样您就可以避免设备上有额外的空间来保存照片库中的记录文件。

      我在下面添加了可用于将录制的文件移动到照片库的确切 API。

      PHPhotoLibrary.shared().performChanges({
          let options = PHAssetResourceCreationOptions()
          options.shouldMoveFile = true
          let creationRequest = PHAssetCreationRequest.forAsset()
          creationRequest.addResource(with: .video, fileURL: outputFileURL, options: options)
      }, completionHandler: { success, error in
          if !success {
              print("Couldn't save the movie to your photo library: \(String(describing: error))")
          }
          cleanup()
         }
      )
      

      上述示例中将文件移动到照片库的主要部分是,

      let options = PHAssetResourceCreationOptions()
      options.shouldMoveFile = true
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多