【问题标题】:iOS: Mute AVAudio when playing embedded clip in WebViewiOS:在 WebView 中播放嵌入剪辑时静音
【发布时间】:2017-03-18 19:05:36
【问题描述】:

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

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

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

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

【问题讨论】:

  • 嗨,您找到解决方案了吗?

标签: ios swift xcode avaudiosession


【解决方案1】:

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

斯威夫特 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. 这仅适用于设备。不要在模拟器上测试

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 2011-03-03
    • 2018-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-30
    相关资源
    最近更新 更多