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

3
我在屏幕上有一个按钮来启动相机,还有一个按钮来停止相机。基本上是用于视频录制。因此,我只是试图设置一个计时器来确定这些视频文件的总持续时间。
//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);
}
}

我需要获取视频的总时长。我正在使用AVAsset来实现,但是一直得到零秒:/ - dicle
改进的语言和标点 - Tab Alleman
1个回答

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获取时间。重置时间后再继续进行操作。

谢谢,但我应该至少有两个小数点来显示时间.. @Mr.T - dicle
你的意思是需要以00、01、02、03秒的格式显示时间吗? - Teja Nandamuri
我想要同时看到秒和分钟,例如 00.05。@Mr.T - dicle
非常感谢。@Mr.T - dicle

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接