gpt4 book ai didi

iphone - 获取时间间隔并在 Objective-C 中播放声音

转载 作者:行者123 更新时间:2023-11-29 04:28:04 25 4
gpt4 key购买 nike

我是对象 C 的新手,我有两个问题,但我在 stackoverflow 上找不到答案。

我的 iOS 应用程序很简单,屏幕上有一个按钮,如果用户点击它,它将:

  1. 播放声音

  2. 获取两次点击之间的时间间隔(以毫秒为单位)。

感谢 Owl,现在获取间隔的代码如下所示:

(编码很长,因为我不明白什么是“UNIX时间戳”,而且我不知道在哪里/如何使用第二个代码。)

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);
}
}

启动应用后,第一次播放声音时有延迟,但第一次点击后效果良好。如何停止这种滞后?

我的播放声音的代码:

在.h

#import <AVFoundation/AVFoundation.h>

AVAudioPlayer *audioPlayer;

以 .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];
}

谢谢

最佳答案

第一次点击,

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

获取 UNIX 时间戳,

第二次点击,

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

获取另一个 UNIX 时间戳,然后从第二个时间戳中减去第一个时间戳。减法的结果就是你的进步。

然后使用此代码获取小时:分钟:秒

double progress;

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

代码:How to convert an NSTimeInterval (seconds) into minutes

更简单

通过两次点击获取两个 NSDate 然后使用,然后不需要减法,只需使用下面的方法即可获取时间间隔。然后计算分钟和秒,如上所示。

- (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate

或者

使用 NSCalender 类中的 components:fromDate:toDate:options: 方法。请参阅:Apple Doc .

编辑:

Jus 进行了快速测试,它对我来说非常有效。

测试代码:

- (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 输出:

2012-08-22 10:46:09.123 Test[778:c07] 1345596369.123665

关于iphone - 获取时间间隔并在 Objective-C 中播放声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12064754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com