app4g
app4g

Reputation: 850

AVSpeechSynthesizer under ios16 not working (same code fine on iOS 12 / iOS 15) on UIKit

This is what I am using for TextToSpeech using AVSpeechSynthesizer and it seems to be working from iOS 12 & iOS 15, but when I try it on iOS 16.1, no voice can be heard using the below code.

I have confirmed that Spoken Content is working (Accessibility -> spoken content -> Speak Selection -> Enabled) and I can get the phone to speak out whole screen of text.

However, it's just not working for my app.

import Foundation
import AVFoundation

struct TTS {
  
//  let synthesizer = AVSpeechSynthesizer()

  static func speak(messages: String) {
    let message = "Hello World"

    let synthesizer = AVSpeechSynthesizer()
    
    let utterance = AVSpeechUtterance(string: messages)
    utterance.rate = AVSpeechUtteranceDefaultSpeechRate

    utterance.postUtteranceDelay = 0.005
    synthesizer.speak(utterance)
    
  }
}

This has helped some, but only for the problem of AVSpeechSynthesizer not working under Xcode simulator.

AVSpeechSynthesizer isn't working under ios16 anymore

The other solutions in that SO doesn't seem to be working for my case.

some of the proposed solution is asking to move the let synthesizer = AVSpeechSynthesizer() out of the function, but when I do that, Xcode complains about Instance member 'synthesizer' cannot be used on type 'TTS'

https://developer.apple.com/forums/thread/712809

I think there's possibility something wrong w/ my code for iOS 16

This is for UiKit and not SwiftUI which other SO ( Swift TTS, no audio-output) has a solution for.

Upvotes: 0

Views: 1400

Answers (1)

app4g
app4g

Reputation: 850

Changed my struct to a class since AVSpeechSynthesizer can't be a local variable. This now works

import Foundation
import AVFoundation

class TTS {
  
  let synthesizer = AVSpeechSynthesizer()
  
  func speak(messages: String) {
    print("[TTS][Speak]\n\(messages)")

    let utterance = AVSpeechUtterance(string: messages)
    utterance.voice = AVSpeechSynthesisVoice(language: "en-US")
    
    utterance.postUtteranceDelay = 0.005
    synthesizer.speak(utterance)
  }
  
}

How to Use

let tts = TTS()
tts.speak(message: "Hello World")

Upvotes: 2

Related Questions