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

ios - 每当我在里面点击我的整个应用程序时播放点击声音


                                            <p><p>在我的应用中,对于按钮点击或任何点击,我需要在用户点击或点击时播放一声哔声。我在 AppDelegate 中添加了这段代码:</p>

<pre><code>var audioPlayer: AVAudioPlayer?
func playSound() {
      let audioFileURL = Bundle.main.url(forResource: &#34;/Sound/music1&#34;, withExtension: &#34;mp3&#34;)
      do {
            try audioPlayer = AVAudioPlayer(contentsOf: audioFileURL!)
      } catch let error {
            print(error.localizedDescription)
      }
      audioPlayer?.play()
    }
</code></pre>

<p>我不知道如何将这些方法合并或传递给我所有的点击和按钮点击以播放哔声。我不想在每个 vc 中添加每个按钮单击。对我的应用中的按钮单击和任何触摸事件的动态解决方案有任何帮助吗?</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>如果您需要不同的手势,您可以在按钮的每个操作中调用函数 playSound(),例如长按,您可以使用手势识别器。</p>

<p>例如,如果您需要在按下按钮时播放简单的哔声,只需在按钮的@IBAction 内调用 playSound(),但如果用户长时间按下按钮,则需要播放错误哔声,所以在您的按钮中添加一个 UILongPressGestureRecognizer ,如下所示:
<a href="/image/65HHL.png" rel="noreferrer noopener nofollow"><img src="/image/65HHL.png" alt="enter image description here"/></a> </p>

<p>因此,您可以将手势识别器链接到您的代码,就像这样的简单@IBAction:</p>

<p> <a href="/image/rmFcQ.png" rel="noreferrer noopener nofollow"><img src="/image/rmFcQ.png" alt="enter image description here"/></a> </p>

<p>但这只是你需要不同的手势,如果你需要一个简单的哔哔声,为什么不试试这个:</p>

<pre><code>@IBAction func testAction(_ sender: UIButton) {
   playSound()
}
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 每当我在里面点击我的整个应用程序时播放点击声音,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/55288083/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/55288083/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 每当我在里面点击我的整个应用程序时播放点击声音