Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/117.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
无法从iOS中的设置URL压缩视频?_Ios_Objective C_Cocoa Touch_Compression_Alassetslibrary - Fatal编程技术网

无法从iOS中的设置URL压缩视频?

无法从iOS中的设置URL压缩视频?,ios,objective-c,cocoa-touch,compression,alassetslibrary,Ios,Objective C,Cocoa Touch,Compression,Alassetslibrary,我从ALASSET获得了视频URL,然后使用imputURL函数将视频转换为LowQuailtyWithinputURL,以压缩视频,但它无法工作。我看到压缩后,视频的大小总是0 此函数用于从视频集获取视频URL: ALAsset *alasset = [allVideos objectAtIndex:i]; ALAssetRepresentation *rep = [alasset defaultRepresentation]; NSString

我从ALASSET获得了视频URL,然后使用imputURL函数将视频转换为LowQuailtyWithinputURL,以压缩视频,但它无法工作。我看到压缩后,视频的大小总是0

此函数用于从视频集获取视频URL:

ALAsset *alasset = [allVideos objectAtIndex:i];
            ALAssetRepresentation *rep = [alasset defaultRepresentation];
            NSString * videoName = [rep filename];

            //compress video data before uploading
            NSURL  *videoURL = [rep url];
            NSLog(@"videoURL is %@",videoURL);


            NSURL *uploadURL = [NSURL fileURLWithPath:[[NSTemporaryDirectory() stringByAppendingPathComponent:videoName] stringByAppendingString:@".mov"]];
            NSLog(@"uploadURL temp is %@",uploadURL);

            // Compress movie first
            [self convertVideoToLowQuailtyWithInputURL:videoURL outputURL:uploadURL handler:^(AVAssetExportSession *session)
             {
                 if (session.status == AVAssetExportSessionStatusCompleted)
                 {
                     // Success
                 }
                 else
                 {
                     // Error Handing

                 }
             }];

            NSString *path = [uploadURL path];
            NSData *data = [[NSFileManager defaultManager] contentsAtPath:path];
            NSLog(@"size after compress video is %d",data.length);
        }
功能压缩视频:

- (void)convertVideoToLowQuailtyWithInputURL:(NSURL*)inputURL
                                   outputURL:(NSURL*)outputURL
                                     handler:(void (^)(AVAssetExportSession*))handler
{
    [[NSFileManager defaultManager] removeItemAtURL:outputURL error:nil];
    AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:inputURL options:nil];
    AVAssetExportSession *session = [[AVAssetExportSession alloc] initWithAsset: urlAsset presetName:AVAssetExportPresetLowQuality];
    session.outputURL = outputURL;
    session.outputFileType = AVFileTypeQuickTimeMovie;
    [session exportAsynchronouslyWithCompletionHandler:^(void)
     {
         handler(session);

     }];
}
当我调用
convertVideoToLowQualityWithinputURL
函数时,我没有看到它触发到
处理程序(会话)

NSLog(@“压缩视频后的大小为%d”,数据长度)始终打印“大小为0”。

我哪里出错了?请给我一些建议。提前感谢。

ConvertVideoToLowQuailtyWithiInputURL
是一种异步方法,这就是为什么它需要一个完成处理程序块。您当前的日志代码不在完成处理程序块中,而是在调用
convertVideoToLowQuailtyWithiInputUrl
之后-这将在
convertVideoToLowQuailtyWithiInputUrl
完成之前运行,因此您将永远不会得到结果


将压缩视频的日志记录(和使用情况)移动到完成块中。

ConvertVideoToLowQuailtyWithiInputUrl
是一种异步方法,这就是它需要完成处理程序块的原因。您当前的日志代码不在完成处理程序块中,而是在调用
convertVideoToLowQuailtyWithiInputUrl
之后-这将在
convertVideoToLowQuailtyWithiInputUrl
完成之前运行,因此您将永远不会得到结果

ALAssetRepresentation* representation = [asset defaultRepresentation];
NSString *fileName =  [NSString stringWithFormat:@"VGA_%@",representation.filename]; //prepend with _VGA to avoid overwriting original.
NSURL *TempLowerQualityFileURL = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:fileName] ];
NSURL *gallery_url = representation.url;
NSLog(@" \r\n PRE-CONVERSION FILE %@ Size =%lld ; URL=%@\r\n",fileName,  representation.size,representation.url );
[self convertVideoToLowQuailtyWithInputURL:representation.url outputURL:TempLowerQualityFileURL handler:^(AVAssetExportSession *session)
{
      if (session.status == AVAssetExportSessionStatusCompleted)
      {
           NSLog(@"\r\n CONVERSION SUCCESS \r\n");
           NSString *path = [TempLowerQualityFileURL path];
           NSData *data = [[NSFileManager defaultManager] contentsAtPath:path];
           NSLog(@" \r\n POST-CONVERSION TEMP FILE %@ Size =%d ; URL=%@\r\n",fileName,  data.length, path );

           ALAssetsLibrary* library = [[ALAssetsLibrary alloc] init];
             [library writeVideoAtPathToSavedPhotosAlbum:TempLowerQualityFileURL completionBlock:^(NSURL *assetURL, NSError *error)
            {
                 if (error)
                 {
                     NSLog(@"Error Saving low quality video to Camera Roll%@", error);
                 }

                 NSLog(@"\r\n temp low quality file exists before = %d", [self fileExistsAtPath:path] );
                 [[NSFileManager defaultManager] removeItemAtURL:TempLowerQualityFileURL error:nil];
                 NSLog(@"\r\n temp low quality file exists after = %d", [self fileExistsAtPath:path] );

                 NSURL *NewAssetUrlInCameraRoll = assetURL;
                 [[VideoThumbManager sharedInstance] replaceLink:representation.url withNewLink:NewAssetUrlInCameraRoll];


              }];//end writeVideoAtPathToSavedPhotosAlbum completion block.

      }
      else
      {
           // Error Handing
           NSLog(@"\r\n CONVERSION ERROR \r\n");

      }
}];//end convert completion block

将压缩视频的记录(和使用)移动到完成块。

SWIFT 3 MP4视频压缩

ALAssetRepresentation* representation = [asset defaultRepresentation];
NSString *fileName =  [NSString stringWithFormat:@"VGA_%@",representation.filename]; //prepend with _VGA to avoid overwriting original.
NSURL *TempLowerQualityFileURL = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:fileName] ];
NSURL *gallery_url = representation.url;
NSLog(@" \r\n PRE-CONVERSION FILE %@ Size =%lld ; URL=%@\r\n",fileName,  representation.size,representation.url );
[self convertVideoToLowQuailtyWithInputURL:representation.url outputURL:TempLowerQualityFileURL handler:^(AVAssetExportSession *session)
{
      if (session.status == AVAssetExportSessionStatusCompleted)
      {
           NSLog(@"\r\n CONVERSION SUCCESS \r\n");
           NSString *path = [TempLowerQualityFileURL path];
           NSData *data = [[NSFileManager defaultManager] contentsAtPath:path];
           NSLog(@" \r\n POST-CONVERSION TEMP FILE %@ Size =%d ; URL=%@\r\n",fileName,  data.length, path );

           ALAssetsLibrary* library = [[ALAssetsLibrary alloc] init];
             [library writeVideoAtPathToSavedPhotosAlbum:TempLowerQualityFileURL completionBlock:^(NSURL *assetURL, NSError *error)
            {
                 if (error)
                 {
                     NSLog(@"Error Saving low quality video to Camera Roll%@", error);
                 }

                 NSLog(@"\r\n temp low quality file exists before = %d", [self fileExistsAtPath:path] );
                 [[NSFileManager defaultManager] removeItemAtURL:TempLowerQualityFileURL error:nil];
                 NSLog(@"\r\n temp low quality file exists after = %d", [self fileExistsAtPath:path] );

                 NSURL *NewAssetUrlInCameraRoll = assetURL;
                 [[VideoThumbManager sharedInstance] replaceLink:representation.url withNewLink:NewAssetUrlInCameraRoll];


              }];//end writeVideoAtPathToSavedPhotosAlbum completion block.

      }
      else
      {
           // Error Handing
           NSLog(@"\r\n CONVERSION ERROR \r\n");

      }
}];//end convert completion block
100%为我工作

此代码使用12 MB到2 MB的URL(文档目录)压缩视频。 我捕获了.mp4格式的视频,压缩代码返回相同格式的视频

保存压缩的函数

func compressVideo(inputURL: URL, outputURL: URL, handler:@escaping (_ exportSession: AVAssetExportSession?)-> Void) {
        let urlAsset = AVURLAsset(url: inputURL, options: nil)
        guard let exportSession = AVAssetExportSession(asset: urlAsset, presetName: AVAssetExportPresetMediumQuality) else {
            handler(nil)
            return
        }

        exportSession.outputURL = outputURL
        exportSession.outputFileType = AVFileTypeQuickTimeMovie // Don't change it to .mp4 format
        exportSession.shouldOptimizeForNetworkUse = false
        exportSession.exportAsynchronously { () -> Void in
            handler(exportSession)
        }
    }
压缩视频的目标URL代码

let filePath = URL(fileURLWithPath: strVideoPath)
        var compressedURL : URL!
        let fileManager = FileManager.default
        do {
            let documentDirectory = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor:nil, create:true)
            compressedURL = documentDirectory.appendingPathComponent("Video.mp4")
        } catch {
            print(error)
        }
    //It is compulsory to remove previous item at same URL. Otherwise it is unable to save file at same URL.    
        do {
            try   fileManager.removeItem(at: compressedURL)
            print("Removed")
        } catch {
            print(error)
        }
呼叫代码

  compressVideo(inputURL: filePath , outputURL: compressedURL) { (exportSession) in
                guard let session = exportSession else {
                    return
                }

                switch session.status {
                case .unknown:
                    break
                case .waiting:
                    break
                case .exporting:
                    break
                case .completed:
                    print(compressedURL)
                    let newData : Data!
                    do {
                        newData = try Data(contentsOf: compressedURL) as Data?
                        print("File size after compression: \(Double((newData?.count)! / 1048576)) mb")
                    } catch {
                        return
                    }

                case .failed:
                    print(exportSession?.error.debugDescription)
                    break
                case .cancelled:
                    break
                }
            }

SWIFT 3 MP4视频压缩

100%为我工作

此代码使用12 MB到2 MB的URL(文档目录)压缩视频。 我捕获了.mp4格式的视频,压缩代码返回相同格式的视频

保存压缩的函数

func compressVideo(inputURL: URL, outputURL: URL, handler:@escaping (_ exportSession: AVAssetExportSession?)-> Void) {
        let urlAsset = AVURLAsset(url: inputURL, options: nil)
        guard let exportSession = AVAssetExportSession(asset: urlAsset, presetName: AVAssetExportPresetMediumQuality) else {
            handler(nil)
            return
        }

        exportSession.outputURL = outputURL
        exportSession.outputFileType = AVFileTypeQuickTimeMovie // Don't change it to .mp4 format
        exportSession.shouldOptimizeForNetworkUse = false
        exportSession.exportAsynchronously { () -> Void in
            handler(exportSession)
        }
    }
压缩视频的目标URL代码

let filePath = URL(fileURLWithPath: strVideoPath)
        var compressedURL : URL!
        let fileManager = FileManager.default
        do {
            let documentDirectory = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor:nil, create:true)
            compressedURL = documentDirectory.appendingPathComponent("Video.mp4")
        } catch {
            print(error)
        }
    //It is compulsory to remove previous item at same URL. Otherwise it is unable to save file at same URL.    
        do {
            try   fileManager.removeItem(at: compressedURL)
            print("Removed")
        } catch {
            print(error)
        }
呼叫代码

  compressVideo(inputURL: filePath , outputURL: compressedURL) { (exportSession) in
                guard let session = exportSession else {
                    return
                }

                switch session.status {
                case .unknown:
                    break
                case .waiting:
                    break
                case .exporting:
                    break
                case .completed:
                    print(compressedURL)
                    let newData : Data!
                    do {
                        newData = try Data(contentsOf: compressedURL) as Data?
                        print("File size after compression: \(Double((newData?.count)! / 1048576)) mb")
                    } catch {
                        return
                    }

                case .failed:
                    print(exportSession?.error.debugDescription)
                    break
                case .cancelled:
                    break
                }
            }