iOS 在完成播放前播放相同的音效

标签 ios audio

我正在为 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/

相关文章:

audio - 使用ffmpeg转码后,我发现音频码率不是我期望的值

c - 如何编写提供频率信息的 iTunes 插件

javascript - Web Audio Api 与 Web Speech Api 集成 - 将扬声器/声卡输出流式传输到语音识别 api

java - 如何将生成的 PCM 字节[]保存到 Android 支持的音频文件?

audio - NAudio问题-管理多播声音文件一个接一个地播放

ios - 如何控制文本字段中文本的外观

ios - Swift 数组 : Keeping the order while filtering an array using another

ios - WKWebView 显示灰色背景并且 pdf 内容在 viewcontroller 开关上变得不可见

iOS App Store 不同账号发布

iphone - ARC 环境中的 Setter 和 Getter