简体   繁体   中英

Audio not available through headphones during WebRTC Video calling

I'm already connected to headphones from the iPhone device but I can't hear sound from the headphones during a video call. It's hearing every time on speakerphone.

please find below the Audio responding to route changes code:

func activateHeadPhonesStatus(){
    NotificationCenter.default.addObserver(self, selector: #selector(audioRouteChangeListener(_:)), name: NSNotification.Name.AVAudioSessionRouteChange, object: nil)
}

@objc func audioRouteChangeListener(_ notification:Notification) {
    guard let userInfo = notification.userInfo,
        let reasonValue = userInfo[AVAudioSessionRouteChangeReasonKey] as? UInt,
        let reason = AVAudioSession.RouteChangeReason(rawValue:reasonValue) else {
            return
    }
    switch reason {
    case .newDeviceAvailable:
        let session = AVAudioSession.sharedInstance()
        for output in session.currentRoute.outputs where output.portType == AVAudioSessionPortHeadphones {
            print("headphone plugged in")
            AppDelObj.providerDelegate.videoCallRTC?.speakerOff()
            break
        }
    case .oldDeviceUnavailable:
        if let previousRoute =
            userInfo[AVAudioSessionRouteChangePreviousRouteKey] as? AVAudioSessionRouteDescription {
            for output in previousRoute.outputs where output.portType == AVAudioSessionPortHeadphones {
                print("headphone pulled out")
                AppDelObj.providerDelegate.videoCallRTC?.speakerOn()
                break
            }
        }
    case .routeConfigurationChange:
        print("routeConfigurationChange")
    case .categoryChange:
        print("categoryChange")
    default: ()
    }
    
}

The most user-friendly way to solve this problem is using AVRoutePickerView, which allows the user to choose the appropriate output. You can just use this wrapper and put it as one of toolbar buttons.

import SwiftUI
import AVKit

struct AudioRoutePickerView: UIViewRepresentable {
    typealias UIViewType = AVRoutePickerView
    
    func makeUIView(context: Context) -> AVRoutePickerView {
        let view = AVRoutePickerView()
        return view
    }
    
    func updateUIView(_ uiView: AVRoutePickerView, context: Context) {
    }
}

You should configure the default audio session to use what you want like the following example:

do {
     try AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .videoChat, options: [.mixWithOthers, .defaultToSpeaker, .allowBluetooth, .allowAirPlay])
 } catch {
   print(error)
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM