如何在两次按钮点击之间设置计时器

时间:2015-10-26 16:52:33

标签: ios objective-c avfoundation media-player alassetslibrary

屏幕上有一个按钮可启动相机,一个按钮可停止相机。基本上它是用于视频录制。所以我只想设置一个计时器来确定这些视频文件的总持续时间。

//start camera

- (IBAction)startCamera:(id)sender {

if (!recording)
{
//----- START RECORDING -----
NSLog(@"START RECORDING");
recording = YES;


//Create temporary URL to record to
NSString *outputPath = [[NSString alloc] initWithFormat:@"%@%@", NSTemporaryDirectory(), @"output.mov"];
NSURL *outputURL = [[NSURL alloc] initFileURLWithPath:outputPath];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:outputPath])
{
}
//Start recording
[MovieFileOutput startRecordingToOutputFileURL:outputURL recordingDelegate:self];     


//stop camera

-(void)stopCamera:(id)sender {

//----- STOP RECORDING -----

NSLog(@"STOP RECORDING");
recording = NO;
[MovieFileOutput stopRecording];


//i have used this for get the time but keep saying 00.00.00
//Create temporary URL to record to
NSString *outputPath = [[NSString alloc] initWithFormat:@"%@%@", NSTemporaryDirectory(), @"output.mov"];
NSURL *outputURL = [[NSURL alloc] initFileURLWithPath:outputPath];
NSFileManager *fileManager = [NSFileManager defaultManager];

AVURLAsset* videoAsset = [AVURLAsset URLAssetWithURL:outputURL options:nil];
CMTime videoDuration = videoAsset.duration;
float videoDurationSeconds = CMTimeGetSeconds(videoDuration);

NSDate* date = [NSDate dateWithTimeIntervalSince1970:videoDurationSeconds];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[dateFormatter setDateFormat:@"HH:mm:ss"];  //we can vary the date string. Ex: "mm:ss"
NSString* result = [dateFormatter stringFromDate:date];
NSLog(@"Duration 2 of this after stopping : %2@",result);
}
}

1 个答案:

答案 0 :(得分:1)

您需要制作自定义计数器方法。你可以尝试这段代码。

创建计时器和计数器属性

@property (nonatomic,strong) NSTimer *startTimer;
@property (assign) NSInteger x;

并在viewDidAppear中给出x 0。

并在开始录制时启动计时器:

 -(IBAction)start:(id)sender{
    [self startReading];

    _startTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f
                                                   target:self
                                                 selector:@selector(count)
                                                 userInfo:nil
                                                  repeats:YES];

}

-(IBAction)stop:(id)sender{
    [self stopReading];

    [_startTimer invalidate];

}

-(void)count{

    NSLog(@"video duration %ld",(long)_x);
    _x=_x+1;
double seconds = fmod(_x, 60.0);
double minutes = fmod(trunc(_x / 60.0), 60.0);
double hours = trunc(_x / 3600.0);
self.timerLabel.text = [NSString stringWithFormat:@"%02.0f:%02.0f:%04.1f", hours, minutes, seconds];

}

你可以从_x获得时间。重置时间,然后再做你的东西。