IOS /目标C NStemporarydirectory()行为

时间:2019-02-13 14:45:32

标签: ios objective-c video mobile

我实际上在开发应用程序,并且其中一项功能能够共享视频和照片。因此,这是一笔交易,我希望用户能够拍摄照片或视频,并将其发送给另一个用户。图片效果不错,但在视频方面却苦苦挣扎。捕获视频的代码:

            // Start recording to a temporary file.
            NSString *outputFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:[@"movie" stringByAppendingPathExtension:@"mov"]];
            [movieFileOutput startRecordingToOutputFileURL:[NSURL fileURLWithPath:outputFilePath] recordingDelegate:self];
        }
    });
}

在发送之前转换视频的代码:

    + (void)convertVideoToMP4:(NSURL*)videoLocalURL
                  success:(void(^)(NSURL *videoLocalURL, NSString *mimetype, CGSize size, double durationInMs))success
                  failure:(void(^)(void))failure
{
    NSParameterAssert(success);
    NSParameterAssert(failure);

    NSURL *outputVideoLocalURL;
    NSString *mimetype;

    // Define a random output URL in the cache foler
    NSString * outputFileName = [NSString stringWithFormat:@"%.0f.mp4",[[NSDate date] timeIntervalSince1970]];
    NSLog(@"ouputFilename");
    NSLog(@"%@", outputFileName);
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSLog(@"%@", paths);
    NSString *cacheRoot = [paths objectAtIndex:0];
    outputVideoLocalURL = [NSURL fileURLWithPath:[cacheRoot stringByAppendingPathComponent:outputFileName]];
    NSLog(@"%@", outputVideoLocalURL);

    NSLog(@"endlog");
    // Convert video container to mp4
    // Use medium quality to save bandwidth
    AVURLAsset* videoAsset = [AVURLAsset URLAssetWithURL:videoLocalURL options:nil];
    NSLog(@"videoLocalURL");
    NSLog(@"%@",videoLocalURL);

    AVAssetExportSession *exportSession = [AVAssetExportSession exportSessionWithAsset:videoAsset presetName:AVAssetExportPresetMediumQuality];
    exportSession.outputURL = outputVideoLocalURL;

    // Check output file types supported by the device
    NSArray *supportedFileTypes = exportSession.supportedFileTypes;
    if ([supportedFileTypes containsObject:AVFileTypeMPEG4])
    {
        exportSession.outputFileType = AVFileTypeMPEG4;
        mimetype = @"video/mp4";
        NSLog(@"%s", "videoIsMp4");
    }
    else
    {
        NSLog(@"[MXTools] convertVideoToMP4: Warning: MPEG-4 file format is not supported. Use QuickTime format.");

        // Fallback to QuickTime format
        exportSession.outputFileType = AVFileTypeQuickTimeMovie;
        mimetype = @"video/quicktime";
    }

    // Export video file
    [exportSession exportAsynchronouslyWithCompletionHandler:^{

        AVAssetExportSessionStatus status = exportSession.status;
        NSLog(@"exportSession.status");
        NSLog(@"%ld",(long)exportSession.status);

        // Come back to the UI thread to avoid race conditions
        dispatch_async(dispatch_get_main_queue(), ^{

            // Check status
            if (status == AVAssetExportSessionStatusCompleted)
            {

                AVURLAsset* asset = [AVURLAsset URLAssetWithURL:outputVideoLocalURL
                                                        options:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                 [NSNumber numberWithBool:YES],
                                                                 AVURLAssetPreferPreciseDurationAndTimingKey,
                                                                 nil]
                                     ];

                double durationInMs = (1000 * CMTimeGetSeconds(asset.duration));

                // Extract the video size
                CGSize videoSize;
                NSArray *videoTracks = [asset tracksWithMediaType:AVMediaTypeVideo];
                NSLog(@"videoTracks");
                NSLog(@"%@",videoTracks);
                if (videoTracks.count > 0)
                {

                    AVAssetTrack *videoTrack = [videoTracks objectAtIndex:0];
                    videoSize = videoTrack.naturalSize;

                    // The operation is complete
                    success(outputVideoLocalURL, mimetype, videoSize, durationInMs);
                }
                else
                {

                    NSLog(@"[MXTools] convertVideoToMP4: Video export failed. Cannot extract video size.");

                    // Remove output file (if any)
                    [[NSFileManager defaultManager] removeItemAtPath:[outputVideoLocalURL path] error:nil];
                    failure();
                }
            }
            else
            {

                NSLog(@"[MXTools] convertVideoToMP4: Video export failed. exportSession.status: %tu", status);

                // Remove output file (if any)
                [[NSFileManager defaultManager] removeItemAtPath:[outputVideoLocalURL path] error:nil];
                failure();
            }
        });

    }];
}

因此,使用图片可以很好地工作,如果用户想要共享iphone中已经存在的视频,它也可以使用,但是当他从应用中捕获视频并尝试共享时,转换失败:exporteSession。状态= 4。

奇怪的是,如果我用绝对路径(例如“ ///var/mobile/Media/DCIM/100APPLE/IMG_0359.MOV”)替换outputFilePath(当前值为NSTemporaryDirectory()),则它可以正常工作,因此我猜测我从temp目录转换的事实与我的问题有关,但是我看不出我能做些什么来解决它。有什么想法吗?

谢谢。

0 个答案:

没有答案