OGeek|极客世界-中国程序员成长平台

标题: iOS:在 WebView 中播放嵌入剪辑时静音 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:18
标题: iOS:在 WebView 中播放嵌入剪辑时静音

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

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

我在 AppDelegate 中使用的是以下内容:

AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
AVAudioSession.sharedInstance().setActive(true)



Best Answer-推荐答案


1.您需要订阅AVAudioSession.interruptionNotification您可以在哪里停止播放音频

swift 4.2

订阅通知

NotificationCenter.default.addObserver(self, selector: #selector(handleAudioSessionInterruption), name: AVAudioSession.interruptionNotification, object: AVAudioSession.sharedInstance())

处理通知

@objc func handleAudioSessionInterruption(_ notification : Notification) {
    guard let userInfo = notification.userInfo as? [String: AnyObject] else { return }
    guard let rawInterruptionType = userInfo[AVAudioSessionInterruptionTypeKey] 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
    }
}

2. 这仅适用于设备。不要在模拟器上测试

关于iOS:在 WebView 中播放嵌入剪辑时静音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42878677/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4