我从下面的代码中调用 playSoundFromBundle 来播放声音(aif 文件)。我有一个声音,只需单击一下,然后声音就会减弱。两种声音都在同一个文件中。有时我得到两次点击然后淡出。意思是,点击,点击......淡入淡出。单击不是应该播放的内容。我猜声音开始(点击声音),被打断然后重新启动(完整的声音......点击/淡入淡出),因为可能正在进行其他处理。它何时发生似乎是随机的。我将声音放在自己的线程上,以避免双击。我还能做些什么来确保声音正确播放吗?
- (void) playSoundFromBundleThreaded:(NSArray*)arr{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *fileName = (NSString*)[arr objectAtIndex:0];
NSString *fileExt = (NSString*)[arr objectAtIndex:1];
NSError *err;
AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath: [[NSBundle mainBundle] pathForResource: fileName ofType: fileExt inDirectory:@"/"]] error: &err];
self.audioPlayer = newPlayer;
self.audioPlayer.numberOfLoops = 0;
self.audioPlayer.volume = .5;
if (self.audioPlayer == nil)
{
NSLog(@"Problem initializing Sound - %@", [err description]);
}
else
{
[self.audioPlayer play];
}
[newPlayer release];
[pool release];
}
- (void) playSoundFromBundle:(NSString*)fileName fileExtension:(NSString*)fileExt{
NSArray *arr = [NSArray arrayWithObjects:fileName, fileExt, nil];
[NSThread detachNewThreadSelector: @selector(playSoundFromBundleThreaded:) toTarget:self withObject:arr];
}