Bharath
Bharath

Reputation: 41

How to use main speaker programmatically in Swift

I'm implementing video chat using webrtc. In that I want use the main speaker when the other participant joins the session. For that, I wrote this code, but I'm getting a low voice volume (means voice coming from ear speaker)

func audioSetting() {
    RTCAudioSession.sharedInstance().isAudioEnabled = true
    let session = AVAudioSession.sharedInstance()
    do {
        try session.setCategory(AVAudioSession.Category.playAndRecord, mode: .videoChat, options: [])

        if self.speakerOn {
            try session.overrideOutputAudioPort(.none)
        }
        else {
            try session.overrideOutputAudioPort(.speaker)
        }

        try session.setActive(true)
        self.speakerOn = !self.speakerOn
    }
    catch let error {
        print("Couldn't set audio to speaker: \(error)")
    }
}

Upvotes: 1

Views: 2024

Answers (1)

HardikDabhi
HardikDabhi

Reputation: 2952

I am working on webRTC with socket.IO,

  func setSpeakerStates(enabled: Bool)
    {
        let session = AVAudioSession.sharedInstance()
        var _: Error?
        try? session.setCategory(AVAudioSession.Category.playAndRecord)
        try? session.setMode(AVAudioSession.Mode.voiceChat)
        if enabled {
            try? session.overrideOutputAudioPort(AVAudioSession.PortOverride.speaker)
        } else {
            try? session.overrideOutputAudioPort(AVAudioSession.PortOverride.none)
        }
        try? session.setActive(true)
    }

Please try this method at the end of the viewdidload after adding audio streaming and video streaming.

Upvotes: 2

Related Questions