菜鸟教程小白 发表于 2022-12-13 16:19:35

ios - iPhone AVAudioPlayer 应用程序在第一次播放时卡住


                                            <p><p>我正在使用 iOS SDK 中的 AVAudioPlayer 在每次点击 tableView 行时播放简短的声音。
我在每一行的按钮上手动制作了 <code>@selector</code> 来触发方法 <code>playSound:(id)receiver {}</code>。从接收器我得到声音 url,所以我可以播放它。</p>

<p>这个方法看起来像这样:</p>

<pre><code>- (void)playSound:(id)sender {
    ;
    UIButton *audioButton = (UIButton *)sender;
    forState:UIControlStateNormal];
    NSString *soundUrl = [] objectForKey:@&#34;sound_url&#34;];

    //here I get mp3 file from http url via NSRequest in NSData
    NSData *soundData = ;
    NSError *error;
    audioPlayer = [ initWithData:soundData error:&amp;error];
    audioPlayer.numberOfLoops = 0;
    if (error) {
      NSLog(@&#34;Error: %@&#34;,);
    }
    else {
      audioPlayer.delegate = self;
      ;
    }
}
</code></pre>

<p>除了第一次播放某些声音外,一切正常。应用程序卡住约 2 秒,然后播放声音。单击声音按钮后,第二个和所有其他声音播放立即生效。</p>

<p>我想知道为什么应用程序启动时第一次播放会卡住大约 2 秒?</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>从你的代码片段来看,<code>audioPlayer</code> 一定是一个 ivar,对吧?</p>

<p>在该方法的顶部,您在现有的 <code>audioPlayer</code> 实例上调用 <code>-prepareToPlay</code>(它可能为 nil,至少在第一次通过时)。</p >

<p>稍后在该方法中,您用一个全新的 AVAudioPlayer 实例替换这个现有的音频播放器。之前的<code>-prepareToPlay</code>就浪费了。而且每个新的 AVAudioPlayer 都会泄漏内存。</p>

<p>我会尝试创建一个 AVAudioPlayer 对象的缓存,而不是缓存声音数据或 URL,每个声音一个。在您的 <code>-playSound:</code> 方法中,获取对表行的适当音频播放器的引用,然后 <code>-play</code>。</p>

<p>您可以使用 <code>-tableView:cellForRowAtIndexPath:</code> 作为获取该行的 AVAudioPlayer 实例的适当点,也许懒惰地创建实例并将其缓存在那里。</p>

<p>您可以尝试将 <code>-tableView:willDisplayCell:forRowAtIndexPath:</code> 作为在行的 AVAudioPlayer 实例上调用 <code>-prepareToPlay</code> 的点。 </p>

<p>或者您可以在 <code>-tableView:cellForRowAtIndexPath:</code> 中进行准备。进行实验,看看哪种效果最好。</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - iPhone AVAudioPlayer 应用程序在第一次播放时卡住,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/3767998/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/3767998/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - iPhone AVAudioPlayer 应用程序在第一次播放时卡住