我正在为 iOS 7 创建一个 iPhone 游戏。我有一个名为 sharedResources 的类,它包含游戏中反复使用的某些数据的副本,包括大约 4 秒长的音效。
所以我正在创建这样的音效:
filePathTD = [[NSBundle mainBundle]
pathForResource:@"towerDamage" ofType:@"aiff"];
fileURLTD = [NSURL fileURLWithPath:filePathTD];
towerDamge = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURLTD
error:&error];
if (error)
NSLog(@"Error: %@", [error localizedDescription]);
然后像这样在其他地方调用它:
[towerDamage play];
我的问题是与我想要调用它的速度相比,音效太长了。因此,当我在它正在播放时调用它时,它不会同时播放,因为它已经在使用中,而且我只有一个副本。
所以我问:在不占用太多内存的情况下同时多次播放一个音效的最佳方法是什么?
我知道我可以制作多个副本,但如果我为每个需要它的角色制作一个副本,我可能有 30 个副本,而我可能最多只需要 5 个。我在想的是只制作 5 个副本,并且只使用当前未使用的副本。但是因为我是 iOS 开发的新手,所以我不确定除了这个 hack 之外是否还有更好的方法来完成这个任务?
最佳答案
在 AVAudioPlayer 实例上使用 prepareToPlay 将预加载声音文件。也许你可以将它们中的一些合理数量加载到一个数组中,然后根据需要循环遍历它们。如果您需要的数量超过分配的数量,那么您当时可以选择将一个新的加载到内存中,或者重新开始播放列表中的第一个。一个更复杂的系统可以根据因素或应用程序中发生的事情在阵列中存储更多或更少的声音。
也许是这样的? (为了简洁起见,我省略了错误检查和其他内容)
//setup the managing class to be
//<AVAudioPlayerDelegate>
///--- instance variables or properties
int nextIndexToPlayInArrayOfSounds = 0;
NSMutableArray *arrayOfSounds = [NSMutableArray array];
int numberOfSoundsNeeded = 10;
//make a method to setup the sounds
for (int i = 0; i < numberOfSoundsNeeded; i++) {
AVAudioPlayer *mySound = [[AVAudioPlayer alloc] initWithContentsOfURL:[[NSBundle mainBundle] URLForResource:[NSString stringWithFormat:@"soundNameOnDisk"] withExtension:@"aiff"] error:NULL];
mySound.delegate = self;
[arrayOfSounds addObject:mySound];
[mySound prepareToPlay];
}
//make a method to play a sound
//and then play the next sound in the list, or if past the end of the array, or play the first one
AVAudioPlayer *nextSoundToPlay;
if (numberOfSoundsNeeded > nextIndexToPlayInArrayOfSounds) {
nextIndexToPlayInArrayOfSounds++;
}else{
nextIndexToPlayInArrayOfSounds = 0;
}
//obviously I'm skipping error checking and nil pointers, etc
nextSoundToPlay = [arrayOfSounds objectAtIndex:nextIndexToPlayInArrayOfSounds ];
[nextSoundToPlay playAtTime:0];
关于iOS 在完成播放前播放相同的音效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23467579/