如何在iPhone应用程序中获取录制视频的持续时间

时间:2013-06-19 06:03:56

标签: iphone objective-c video-recording

我正在iPhone中录制视频我希望获得录制的录制持续时间。有没有办法获得录制的视频持续时间。

以下是我将录制的视频与路径一起获取的代码。

if ([type isEqualToString:(NSString *)kUTTypeVideo] || [type isEqualToString:(NSString *)kUTTypeMovie])
{
    NSURL*videoURL = [info objectForKey:UIImagePickerControllerMediaURL];

    videoData = [[NSData dataWithContentsOfURL:videoURL] retain];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease];
    [dateFormat setDateFormat:@"dd-MM-yyyy_HH:mm:SS"];

    NSDate *now = [[[NSDate alloc] init] autorelease];
    NSDate* theDate = [dateFormat stringFromDate:now];

    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"Default Album"];

    if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
        [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil];

    NSString*testUser=TitleTextField.text;

    NSString *videopath= [[[NSString alloc] initWithString:[NSString stringWithFormat:@"%@/%@.mov",documentsDirectory,testUser]] autorelease];

    BOOL success = [videoData writeToFile:videopath atomically:NO];

    // Alert for showing the record video

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"You have recorded a video"
                                                   delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];

    recordedVideoLabel.text=@"You have recorded Video";
}

2 个答案:

答案 0 :(得分:12)

使用AVAssets可以轻松完成

AVURLAsset *avUrl = [AVURLAsset assetWithURL:@"Here comes the url of the video"];
CMTime time = [avUrl duration];
int seconds = ceil(time.value/time.timescale);

您需要在项目中链接CoreMedia和AVFoundation框架

答案 1 :(得分:0)

这对我来说可以节省时间,您可以将此方法添加到您的代码中:

-(float) getDurationInSecondsForVideoPath:(NSString*)videoPath {
   NSURL * videoURL = [NSURL URLWithString: videoPath];
   AVURLAsset * avAsset = [AVURLAsset videoURL];
   CMTime avDuration = [avAsset duration];
   float avDurationInSeconds = CMTimeGetSeconds(avDuration);
   return avDurationInSeconds;
}

注意:在使用该方法之前,请确保videoPath有效,否则该方法将返回0.0000或nan

有关更多信息:AVAsynchronousKeyValueLoadingAVURLAssetAVAsset