iosswiftavfoundationavspeechutterance

AVSpeechSynthesizer plays sound with phone call speaker instead of bottom speaker


I created a function to read a text and play it with bottom speaker on the iPhone because the bottom volume is higher than phone call speaker, but it plays with phone call speaker with low volume.

@discardableResult
    func speechSentence(_ text: String) -> Bool {
        var utterance: AVSpeechUtterance!
        let synthesizer = AVSpeechSynthesizer()
        utterance = AVSpeechUtterance(string: text)
        utterance.voice = AVSpeechSynthesisVoice(language: "en-US")
        utterance.rate = AVSpeechUtteranceDefaultSpeechRate
        synthesizer.speak(utterance)
        
        return true
    }

there isn't any other code or configuration on the project.

how can I solve this problem?


Solution

  • I found the problem. I must configuredAVAudioSession as well. and I just add below line on my code and it worked.

    try? AVAudioSession.sharedInstance().setCategory(.playback, mode: .voicePrompt, options: [])
    

    the final code is:

    @discardableResult
        func speechSentence(_ text: String) -> Bool {
            try? AVAudioSession.sharedInstance().setCategory(.playback, mode: .voicePrompt, options: [])
            var utterance: AVSpeechUtterance!
            let synthesizer = AVSpeechSynthesizer()
            utterance = AVSpeechUtterance(string: text)
            utterance.voice = AVSpeechSynthesisVoice(language: "en-US")
            utterance.rate = AVSpeechUtteranceDefaultSpeechRate
            synthesizer.speak(utterance)
            
            return true
        }