【发布时间】:2011-04-22 11:11:30
【问题描述】:
我创建了一个音乐应用程序,当物体与网格边缘碰撞时,它会播放 9 种声音中的一种。这在模拟器上绝对完美无缺,但在第 4 代设备上不能完全同步,在 iPhone 3g 上完全不同步。
不同步是指混响每 0.2 秒发生一次,以匹配网格移动的速度,并且由于设备上的混响不同时,声音听起来不正确。从 iPhone 3g 中也可以看出,网格肯定不是每 0.2 秒重绘一次——它要慢得多。
这是基本代码:
- (void)startTime {
[musicTimer setFireDate:[NSDate distantFuture]];
musicTimer = [NSTimer scheduledTimerWithTimeInterval: 0.01
target: self
selector: @selector(checkTime)
userInfo: nil
repeats: YES];
}
- (void)checkTime {
float timeSince = [[NSDate date] timeIntervalSinceDate:lastPlayed];
if(timeSince >= 0.2){
[self repositionBlocks];
}
}
- (void)repositionBlocks {
//Check which sounds need to play and call the play function on each of them
//The following line would play the sound if a collision occurred
Sound *sound = [[Sound alloc] init];
[sound play:@"01.wav"];
[sound release];
[self redrawGrid]; //Redraws the grid with the new positions
[lastPlayed release];
lastPlayed = [[NSDate date] retain];
}
这是我的 Sound 类中的播放函数
- (void)play:(NSString *)soundFile {
NSString *path;
NSString *fileName = [NSString stringWithFormat:@"/%@", soundFile];
path = [NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] resourcePath], fileName];
SystemSoundID soundID;
NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);
AudioServicesPlaySystemSound(soundID);
[filePath release];
}
如果有人可以帮助解决这个问题,我将非常感激
谢谢
编辑:我做了一些测试并将其缩小到 NSTimer 的问题,在模拟器上它每 0.2 秒触发一次,但在设备上它每 0.4 - 0.6 秒触发一次。我在互联网上搜索过,有很多关于 NSTimers 不准确且不应该用于此目的的信息,但我找不到任何替代方案。
【问题讨论】:
-
只是好奇,但为什么将 NSTimer 设置为 0.01,然后在 checkTime 中检查 0.2? NSTimer 触发的频率不是比你需要的多吗?
-
最初我尝试让它每 0.2 秒触发一次,但我遇到了同样的问题,我在某个地方阅读了我应该更频繁地触发并检查是否已经过了 0.2 秒。无论哪种方式,问题似乎都是一样的
标签: iphone objective-c audio nstimer audiotoolbox