如何从iOS的现场照片中获取视频



我正在尝试弄清楚它,但找不到任何有用的信息。我只找到了这个:

PHAssetResourceManager.defaultManager().writeDataForAssetResource(assetRes, 
toFile: fileURL, options: nil, completionHandler: 
{
     // Video file has been written to path specified via fileURL
}

,但我很ham愧地说我不知道该如何发挥作用。我已经创建了一个uiimagePickerController并从相机卷中加载了图像。

使用此代码从现场照片获取视频:

- (void)videoUrlForLivePhotoAsset:(PHAsset*)asset withCompletionBlock:(void (^)(NSURL* url))completionBlock{
    if([asset isKindOfClass:[PHAsset class]]){
        NSString* identifier = [(PHAsset*)asset localIdentifier];
        NSString* filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mov",[NSString stringWithFormat:@"%.0f",[[NSDate date] timeIntervalSince1970]]]];
        NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
        PHLivePhotoRequestOptions* options = [PHLivePhotoRequestOptions new];
        options.deliveryMode = PHImageRequestOptionsDeliveryModeFastFormat;
        options.networkAccessAllowed = YES;
        [[PHImageManager defaultManager] requestLivePhotoForAsset:asset targetSize:[UIScreen mainScreen].bounds.size contentMode:PHImageContentModeDefault options:options resultHandler:^(PHLivePhoto * _Nullable livePhoto, NSDictionary * _Nullable info) {
            if(livePhoto){
                NSArray* assetResources = [PHAssetResource assetResourcesForLivePhoto:livePhoto];
                PHAssetResource* videoResource = nil;
                for(PHAssetResource* resource in assetResources){
                    if (resource.type == PHAssetResourceTypePairedVideo) {
                        videoResource = resource;
                        break;
                    }
                }
                if(videoResource){
                    [[PHAssetResourceManager defaultManager] writeDataForAssetResource:videoResource toFile:fileUrl options:nil completionHandler:^(NSError * _Nullable error) {
                        if(!error){
                            completionBlock(fileUrl);
                        }else{
                            completionBlock(nil);
                        }
                    }];
                }else{
                    completionBlock(nil);
                }
            }else{
                completionBlock(nil);
            }
        }];
    }else{
        completionBlock(nil);
    }
}

基本上您要做的是首先需要从PHAsset获取PHLivePhoto对象。之后,您将必须在实时照片中遍历所有资产资源,并检查它是否为PHAssetResourceTypePairedVideo

如果是,您有视频。现在,您将需要像我在这里一样将其保存到一些临时目录中,并将此文件用于任何目的。

要播放此视频,您可以使用以下代码:

NSURL *videoURL = [NSURL fileURLWithPath:fileUrl];
AVPlayer *player = [AVPlayer playerWithURL:videoURL];
AVPlayerViewController *playerViewController = [AVPlayerViewController new];
playerViewController.player = player;
[self presentViewController:playerViewController animated:YES completion:nil];

随时询问您是否需要任何澄清。

p.s .- 我对此方法进行了一些更改,以删除应用程序代码的依赖性,因此未经测试的代码,但是我觉得它应该按预期工作。

swift 4版本

import Photos
import MobileCoreServices
// <UIImagePickerControllerDelegate, UINavigationControllerDelegate>
@IBAction func showImagePicker(sender: UIButton) {
    let picker = UIImagePickerController()
    picker.delegate = self;
    picker.allowsEditing = false;
    picker.sourceType = .photoLibrary;
    picker.mediaTypes = [kUTTypeLivePhoto as String, kUTTypeImage as String];
    present(picker, animated: true, completion: nil);
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    guard
        let livePhoto = info[UIImagePickerControllerLivePhoto] as? PHLivePhoto,
        let photoDir = generateFolderForLivePhotoResources()
        else {
            return;
    }
    let assetResources = PHAssetResource.assetResources(for: livePhoto)
    for resource in assetResources {
        // SAVE FROM BUFFER
//            let buffer = NSMutableData()
//            PHAssetResourceManager.default().requestData(for: resource, options: nil, dataReceivedHandler: { (chunk) in
//                buffer.append(chunk)
//            }, completionHandler: {[weak self] error in
//                self?.saveAssetResource(resource: resource, inDirectory: photoDir, buffer: buffer, maybeError: error)
//            })
        // SAVE DIRECTLY
        saveAssetResource(resource: resource, inDirectory: photoDir, buffer: nil, maybeError: nil)
    }
    picker.dismiss(animated: true) {}
}
func saveAssetResource(
    resource: PHAssetResource,
    inDirectory: NSURL,
    buffer: NSMutableData?, maybeError: Error?
    ) -> Void {
    guard maybeError == nil else {
        print("Could not request data for resource: (resource), error: (String(describing: maybeError))")
        return
    }
    let maybeExt = UTTypeCopyPreferredTagWithClass(
        resource.uniformTypeIdentifier as CFString,
        kUTTagClassFilenameExtension
        )?.takeRetainedValue()
    guard let ext = maybeExt else {
        return
    }
    guard var fileUrl = inDirectory.appendingPathComponent(NSUUID().uuidString) else {
        print("file url error")
        return
    }
    fileUrl = fileUrl.appendingPathExtension(ext as String)
    if let buffer = buffer, buffer.write(to: fileUrl, atomically: true) {
        print("Saved resource form buffer (resource) to filepath (String(describing: fileUrl))")
    } else {
        PHAssetResourceManager.default().writeData(for: resource, toFile: fileUrl, options: nil) { (error) in
            print("Saved resource directly (resource) to filepath (String(describing: fileUrl))")
        }
    }
}
func generateFolderForLivePhotoResources() -> NSURL? {
    let photoDir = NSURL(
        // NB: Files in NSTemporaryDirectory() are automatically cleaned up by the OS
        fileURLWithPath: NSTemporaryDirectory(),
        isDirectory: true
        ).appendingPathComponent(NSUUID().uuidString)
    let fileManager = FileManager()
    // we need to specify type as ()? as otherwise the compiler generates a warning
    let success : ()? = try? fileManager.createDirectory(
        at: photoDir!,
        withIntermediateDirectories: true,
        attributes: nil
    )
    return success != nil ? photoDir! as NSURL : nil
}

在iOS

上实时照片API在深度教程中

这个问题有点混乱

首先,如果您想挑选实时照片并播放实时照片。我建议您使用照片框架而不是UIimagePickerController。这样,您可以获取资产并拥有更多的控制权。然后,您可以通过将startPlayback(with:)设置为hintfull

您可以在此处引用代码:

  • github repo livepreview向您展示如何选择实时照片并播放它。

第二,如果要将实时照片转换为MOV,则粘贴的代码将起作用,如果您想直接玩Mov,则可能需要使用Avplayer

加上WWDC使用照片框架提供示例应用

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
 let phAsset = info[.phAsset] as? PHAsset
 imagePickerController.dismiss(animated: true, completion: nil)
 let style = phAsset?.playbackStyle
  if(style != .livePhoto) {
         print("This is not a live photo")
         return
  }
  let filePath = NSTemporaryDirectory() + String(format: "%.0f", NSDate().timeIntervalSince1970) + "_.mov"
  let fileURL = NSURL(fileURLWithPath: filePath)
  let options = PHLivePhotoRequestOptions()
  options.deliveryMode = .fastFormat
  options.isNetworkAccessAllowed = true
PHImageManager.default().requestLivePhoto(for: phAsset!, targetSize: CGSize(width: 1920, height: 1080), contentMode: PHImageContentMode.default, options: options) { livePhoto, info in
        if((livePhoto) != nil) {
           let assetResources = PHAssetResource.assetResources(for: livePhoto!)
           var videoResource : PHAssetResource?
           for resources in assetResources {
               if(resources.type == .pairedVideo) {
                    videoResource = resources
                    break
               }
            }
            guard let videoResource = videoResource else {
                fatalError("video resource is nil")
            }
            PHAssetResourceManager.default().writeData(for: videoResource, toFile: fileURL as URL, options: nil) { error in                   
                let avAsset : AVAsset = AVAsset(url: fileURL as URL)
                 DispatchQueue.main.async { [self] in
                        // Whatever you do using fileURL or avAsset.
                 }
             }
                
         }
    }
}

swift 5

func videoUrlForLivePhotoAsset(asset: PHAsset, completionHandler: @escaping (_ result: URL?) -> Void) {
            
    print("videoUrlForLivePhotoAsset: (asset)")
    
    let options : PHLivePhotoRequestOptions = PHLivePhotoRequestOptions.init()
    
    options.deliveryMode = .fastFormat
    options.isNetworkAccessAllowed = true
    
    PHImageManager.default().requestLivePhoto(for: asset, targetSize: UIScreen.main.bounds.size, contentMode: .default, options: options) { (livePhoto, info) in
        
        if livePhoto != nil {
            
            let assetResources : [PHAssetResource] = PHAssetResource.assetResources(for: livePhoto!)
            
            var videoResource : PHAssetResource?
            
            for resource in assetResources {
                
                if resource.type == .pairedVideo {
                    
                    videoResource = resource
                    break
                    
                }
                
            }
            
            guard let photoDir = self.generateFolderForLivePhotoResources() else {
                return
            }
            
            print("videoResource: (videoResource)")
            
            if videoResource != nil {
                
                self.saveAssetResource(resource: videoResource!, inDirectory: photoDir, buffer: nil, maybeError: nil) { (fileUrl) in
                    
                    completionHandler(fileUrl)
                }
                                                            
            }
            
        } else {
            
            completionHandler(nil)
        }
        
    }
    
}
func saveAssetResource(
    resource: PHAssetResource,
    inDirectory: NSURL,
    buffer: NSMutableData?, maybeError: Error?, completionHandler: @escaping (_ result: URL?) -> Void) {
    
    guard maybeError == nil else {
        print("Could not request data for resource: (resource), error: (String(describing: maybeError))")
        return
    }
    let maybeExt = UTTypeCopyPreferredTagWithClass(
        resource.uniformTypeIdentifier as CFString,
        kUTTagClassFilenameExtension
        )?.takeRetainedValue()
    guard let ext = maybeExt else {
        return
    }
    guard var fileUrl = inDirectory.appendingPathComponent(NSUUID().uuidString) else {
        print("file url error")
        return
    }
    fileUrl = fileUrl.appendingPathExtension(ext as String)
    if let buffer = buffer, buffer.write(to: fileUrl, atomically: true) {
        
        print("Saved resource form buffer (resource) to filepath (String(describing: fileUrl))")
        completionHandler(fileUrl)
        
    } else {
        PHAssetResourceManager.default().writeData(for: resource, toFile: fileUrl, options: nil) { (error) in
            print("Saved resource directly (resource) to filepath (String(describing: fileUrl))")
            if error == nil {
                
                completionHandler(fileUrl)
            } else {
                completionHandler(nil)
            }
        }
    }
    
}
func generateFolderForLivePhotoResources() -> NSURL? {
    
    let photoDir = NSURL(
        // NB: Files in NSTemporaryDirectory() are automatically cleaned up by the OS
        fileURLWithPath: NSTemporaryDirectory(),
        isDirectory: true
        ).appendingPathComponent(NSUUID().uuidString)
    let fileManager = FileManager()
    // we need to specify type as ()? as otherwise the compiler generates a warning
    let success : ()? = try? fileManager.createDirectory(
        at: photoDir!,
        withIntermediateDirectories: true,
        attributes: nil
    )
    return success != nil ? photoDir! as NSURL : nil
    
}

调用以下内容:

let asset = PHAsset.init()
                    
self.videoUrlForLivePhotoAsset(asset: asset!) { (url) in
                        
    print("url: (url)")
}

注意:您需要清理临时和文档目录,然后删除文件。

最新更新