Я на самом деле работаю над приложением, и одна из функций - возможность обмениваться видео и фотографиями.Итак, вот сделка, я хочу, чтобы пользователь мог сделать снимок или видео и отправить его другому пользователю.Картинки работают нормально, но я борюсь с видео. Код, который захватывает видео:
// 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.status = 4.
Странно то, что если я заменю outputFilePath (текущее значение которого - NSTeilitaryDirectory ()) с абсолютным путем, например, "///var/mobile/Media/DCIM/100APPLE/IMG_0359.MOV", он будет работать отличнотак что я предполагаю, что тот факт, что я конвертирую из временного каталога, как-то связан с моей проблемой, но я не вижу, что я могу сделать, чтобы это исправить.Есть мысли?
Заранее спасибо.