菜鸟教程小白 发表于 2022-12-12 22:11:45

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


                                            <p><p>我正在为 iOS 7 创建一个 iPhone 游戏。我有一个名为 sharedResources 的类,其中包含在游戏中反复使用的某些数据的副本,包括 4 秒长的音效。</p>

<p>所以我正在创建这样的音效:</p>

<pre><code>    filePathTD = [
               pathForResource:@&#34;towerDamage&#34; ofType:@&#34;aiff&#34;];
    fileURLTD = ;

    towerDamge = [ initWithContentsOfURL:fileURLTD
                                                    error:&amp;error];
    if (error)
      NSLog(@&#34;Error: %@&#34;, );
</code></pre>

<p>然后像这样在其他地方调用它:</p>

<pre><code>;
</code></pre>

<p>我的问题是与我想调用它的速度相比,声音效果很长。因此,当我在它已经在播放时调用它时,它不会同时播放,因为它已经在使用并且我只有一个副本。</p>

<p>所以我问:在不占用太多内存的情况下同时播放多个音效的最佳方式是什么?</p>

<p>我知道我可以制作多个副本,但如果我为每个需要它的角色制作一个副本,我可能只需要最多 5 个副本,而我可能有 30 个副本。我的想法是只制作 5 个副本,并且只使用当前未使用的副本。但是由于我是 iOS 开发的新手,我不确定除了这个 hack 是否有更好的方法来完成这项任务? </p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>在 AVAudioPlayer 实例上使用 prepareToPlay 将预加载声音文件。也许您可以将一些合理数量的它们加载到一个数组中,然后根据需要循环它们。如果您需要的数量超过分配的数量,那么您当时选择将一个新的加载到内存中,或者重新开始播放列表中的第一个。更复杂的系统可以根据因素或应用程序中发生的情况在数组中存储或多或少的声音。</p>

<p>也许是这样的? (为了简洁起见,我省略了错误检查和什么)</p>

<pre><code>//setup the managing class to be
//&lt;AVAudioPlayerDelegate&gt;

///--- instance variables or properties
int nextIndexToPlayInArrayOfSounds = 0;
NSMutableArray *arrayOfSounds = ;
int numberOfSoundsNeeded = 10;


//make a method to setup the sounds
for (int i = 0; i &lt; numberOfSoundsNeeded; i++) {

    AVAudioPlayer *mySound = [ initWithContentsOfURL:[ URLForResource: withExtension:@&#34;aiff&#34;] error:NULL];
    mySound.delegate = self;
    ;
    ;


}

//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 &gt; nextIndexToPlayInArrayOfSounds) {
    nextIndexToPlayInArrayOfSounds++;
}else{
    nextIndexToPlayInArrayOfSounds = 0;
}

//obviously I&#39;m skipping error checking and nil pointers, etc
nextSoundToPlay = ;
;
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于iOS在播放完成前播放相同的音效,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/23467579/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/23467579/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: iOS在播放完成前播放相同的音效