菜鸟教程小白 发表于 2022-12-11 19:18:04

iOS:在 WebView 中播放嵌入剪辑时静音


                                            <p><p>在我的应用程序中,我正在使用 AVAudioSession 播放音频流,它会在应用程序启动时自动开始播放。</p>

<p>如果用户导航,则在应用程序的另一部分,有一个 webView ,其中可能包含来自 youtube、soundcloud 的嵌入剪辑,任何可能包含声音的内容。
我希望主音频流暂停,以防用户选择播放 webview 中的声音。现在,如果用户选择在 webView 中播放剪辑,声音就会混合,这很烦人,用户必须手动暂停主流。
有没有办法防止这种情况?如果用户选择收听嵌入的剪辑,我需要静音或暂停主流。</p>

<p>我在 AppDelegate 中使用的是以下内容:</p>

<pre><code>AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
AVAudioSession.sharedInstance().setActive(true)
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p><strong>1.</strong>您需要订阅<a href="https://developer.apple.com/documentation/avfoundation/avaudiosession/1616596-interruptionnotification" rel="noreferrer noopener nofollow">AVAudioSession.interruptionNotification</a>您可以在哪里停止播放音频</p>

<p><em> swift4.2</em></p>

<h2>订阅通知</h2>

<pre><code>NotificationCenter.default.addObserver(self, selector: #selector(handleAudioSessionInterruption), name: AVAudioSession.interruptionNotification, object: AVAudioSession.sharedInstance())
</code></pre>

<h2>处理通知</h2>

<pre><code>@objc func handleAudioSessionInterruption(_ notification : Notification) {
    guard let userInfo = notification.userInfo as? else { return }
    guard let rawInterruptionType = userInfo as? NSNumber else { return }
    guard let interruptionType = AVAudioSession.InterruptionType(rawValue: rawInterruptionType.uintValue) else { return }

    switch interruptionType {
    case .began:
      //stop play your audio
    case .ended: //interruption ended
      //do something if needed
    }
}
</code></pre>

<p><strong>2.</strong> 这仅适用于设备。不要在模拟器上测试</p></p>
                                   
                                                <p style="font-size: 20px;">关于iOS:在 WebView 中播放嵌入剪辑时静音,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/42878677/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/42878677/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: iOS:在 WebView 中播放嵌入剪辑时静音