0

I am designing an iOS application using PJSIP for VOIP Calling,

I start the call on speaker and on a button press i am able to make the call on normal microphone, but i am unable to make it on speaker again after pressing the speaker button.

I have used the following code to achieve that functionality :-

if sender.titleLabel?.text == "Speaker"{

            do {
                try audioSession.overrideOutputAudioPort(.none)
                try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
                try audioSession.setMode(AVAudioSessionModeVoiceChat)
                try audioSession.setActive(true)
            } catch {
                print("AVAudioSession cannot be set: \(error)")
            }
        }else{
            do {
                try audioSession.overrideOutputAudioPort(.speaker)
                try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
                try audioSession.setMode(AVAudioSessionModeVoiceChat)
                try audioSession.setActive(true)
            } catch {
                print("AVAudioSession cannot be set: \(error)")
            }
        }
Himanshu
  • 2,832
  • 4
  • 23
  • 51

1 Answers1

0

Im not sure but I think your code will work while using NSNotificationCenter. Send notificaion for speaker in your if statement, and one notification for that else code.

var speaker = false

on press button action:

if speaker == false {
    NSNotificationCenter.defaultCenter().postNotificationName("speakerON", object: nil)

} else {
    NSNotificationCenter.defaultCenter().postNotificationName("speakerOFF", object: nil)

}

on viewDidLoad:

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(_:)), name:"speakerON", object: nil)

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(_:)), name:"speakerOFF", object: nil)

your functions:

func speakerON() {
try audioSession.overrideOutputAudioPort(.none)
                try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
                try audioSession.setMode(AVAudioSessionModeVoiceChat)
                try audioSession.setActive(true)
}

func speakerOFF() {
               try audioSession.overrideOutputAudioPort(.speaker)
                try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
                try audioSession.setMode(AVAudioSessionModeVoiceChat)
                try audioSession.setActive(true)
}

Please see this link if you want to learn more about NSNotificationCenter:

https://stackoverflow.com/questions/24049020/nsnotificationcenter-addobserver-in-swift

Egzon P.
  • 4,498
  • 3
  • 32
  • 31