Search code examples
iosswifttwiliocallkit

Play audio during phone call


I've created an app in Swift that uses Twilio & CallKit to make outgoing phone calls. During the phone call, I would like to play audio through the phone's ear speaker such as "You have been on this call for 2 minutes..." or at the least an one of the built in system audio sounds.

It would work similarly to how navigations apps work when they announce directions when you are on a call

How can I make this happen?

I've looked at some similar questions on here, but I couldn't get an answer or updated answer.


Solution

  • Found out one way to do this is by using the built in AVSpeechSynthesizer. Check out the code below

    public func sayMessage(message: String) {
        do {
            try setCategory(AVAudioSessionCategoryPlayAndRecord)
            try setActive(true)
            let synth = AVSpeechSynthesizer()
            print("Routes:: \(currentRoute.outputs)")
            if let currentChannels = currentRoute.outputs.first?.channels {
                synth.outputChannels = currentChannels
                print("Found channels \(currentChannels)")
            }
            let myUtterance = AVSpeechUtterance(string: message)
            synth.speak(myUtterance)
    
        } catch {
            print(error)
        }
    }