我的应用程序在特定时间检测音频,例如 10:00AM(startTime) -10:30AM(endTime) 等。现在当当前时间到达开始时间(意味着当前时间也是上午 10:00)时如何调用音频检测过程并在 (endTime)10:30 AM 停止检测过程。假设另一个时间间隔从 10:15AM(startTime) - 10:45AM(endTime) 开始,如何将 endTime 从 10:30AM 更新到 10:45AM。如何检查当前时间何时到达 startTime 和 endTime。请帮我解决紧急问题。谢谢我的代码是
ViewController.h
@interface ViewController : UIViewController
{
BOOL IsListening;
}
//session数组是包含程序开始和结束时间的字典数组。
ViewController.m
-(void)viewDidLoad
{
[super viewDidLoad];
NSTimer* listener_timer = [NSTimer scheduledTimerWithTimeInterval: 10.0 target: self
selector: @selector(listeningHandler:) userInfo: nil repeats: YES];
}
-(void)listeningHandler:(NSTimer*)time
{
if (!IsListening)
{
double currentTime=[[NSDate date] timeIntervalSince1970];
for (NSDictionary * session in SessionsArray)
{
double startTime=[[session objectForKey:@“startTime”] doubleValue];
double endTime=[[session objectForKey:@“endTime”] doubleValue];
if (currentTime > startTime && currentTime < endTime)
{
//start listening.
IsListening =YES;
/*
//detection process code
*/
NSDate *fireDate = [NSDate dateWithTimeIntervalSinceNow:endTime];
NSTimer *timer = [[NSTimer alloc] initWithFireDate:fireDate
interval:5
target:nil
selector:@selector(fireEndtimeAlarm)
userInfo:nil
repeats:YES];
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
[runLoop addTimer:timer forMode:NSDefaultRunLoopMode];
}
}
}
else
{
double currentTime=[[NSDate date] timeIntervalSince1970];
for (NSDictionary * session in SessionsArray)
{
double startTime=[[session objectForKey:@"startTime"] doubleValue];
double endTime=[[session objectForKey:@"endTime”] doubleValue];
if (currentTime > startTime && currentTime < endTime)
{
// in between session
IsListening =YES;
/*
//detection process code
*/
}
}
}
}
-(void)fireEndtimeAlarm
{
IsListening = NO;
//stop detecting process at endTime
}
最佳答案
在 ios 中启动定时器和停止定时器
start Timer
timer= [NSTimer scheduledTimerWithTimeInterval:60.0f
target: self
selector: @selector(methodFromTimer)
userInfo: nil
repeats: YES];
stop timer
[timer invalidate];
timer=nil;
关于ios - 如何在 iOS 中的特定时间启动和停止计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29331825/