0

I am new to Object C, and I have two questions but I can not find the answers on stackoverflow.

My iOS app is simple, one button on the screen, and if user tap it, it will:

  1. play a sound

  2. get the time interval between 2 taps in millisecond.

Thanks to Owl, now the code to get the interval look like this:

(Long coding since I don't understand what is "UNIX time stamp" and I don't know where/how to use the second code.)

double dt1;
double dt2;

-(IBAction)Beated:(id)sender{
   If (FB == 1) {
      FB = 2;
      NSDate *date = [NSDate date];
      NSTimeInterval ti = [date timeIntervalSince1970];
      dt1 = ti;
   } else {
      FB = 1
      NSDate *date = [NSDate date];
      NSTimeInterval ti = [date timeIntervalSince1970];
      dt2 = ti;
      double progress;
      progress = dt2 - dt1;
      int timeInMs = trunc(progress * 1000);
      NSLog(@"Interval %d", timeInMs);
   }
}

And after start the app, there is a lag when the sound was played for the first time, but it works good after the first tap. How to stop that lag?

My code to play the sound:

in .h

#import <AVFoundation/AVFoundation.h>

and

AVAudioPlayer *audioPlayer;

in .m

 -(IBAction)Beated:(id)sender {
       NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/ssn.wav",     [[NSBundle mainBundle] resourcePath]]];
       NSError*error;
       audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url  error:$error];
       audioPlayer.numberOfLoops = 0;
       [audioPlayer play];
}

Thanks

user1607767
  • 127
  • 6

1 Answers1

1

First tap,

NSDate *date = [NSDate date];
NSTimeInterval ti = [date timeIntervalSince1970];

Get UNIX time stamp,

Second tap,

NSDate *date = [NSDate date];
NSTimeInterval ti = [date timeIntervalSince1970];

Get another UNIX time stamp, then subtract first from second time stamp. The product of subtraction becomes your progress.

then use this code to get the hour:minute:second

double progress;

 int minutes = floor(progress/60);
 int seconds = trunc(progress - minutes * 60);

Code courtesy : How to convert an NSTimeInterval (seconds) into minutes

Easier

Get two NSDate from two taps and then use, Then no subtraction needed, just use below method to get time interval. and then calculate minutes and second as shown above.

- (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate

Alternatively

Use components:fromDate:toDate:options: method from NSCalender class. See : Apple Doc.

Edit :

Jus did a quick test, and it worked perfectly for me.

Test Code :

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.

    NSDate *date = [NSDate date];
    NSTimeInterval ti = [date timeIntervalSince1970];

    NSLog(@"%f",ti);

    return YES;
}

NSLog Output :

2012-08-22 10:46:09.123 Test[778:c07] 1345596369.123665
Community
  • 1
  • 1
TeaCupApp
  • 11,316
  • 18
  • 70
  • 150