AVSpeechSynthesizer language

2.3k Views Asked by At

In my app I'm using AVSpeechSynthesizer, the text speeches is russian, the problem is when I'm changing system language to English the text pronounce with english accent, sounds like transcription of russian language. How can I manage this problem?

here is some code

    utterance.voice = AVSpeechSynthesisVoice(language: "ru-Ru")
    synthesizer.pauseSpeaking(at: .word)
    utterance = AVSpeechUtterance(string: "Какой-то текст который нужно произнести")
    synthesizer.speak(utterance)
1

There are 1 best solutions below

6
On

Maybe it will be helpful for somebody, I found solution, but it looks like workaround before speaking I change AppLanguage, here is the code

    UserDefaults.standard.set(["ru"], forKey: "AppleLanguages")
    UserDefaults.standard.synchronize()
    utterance.voice = AVSpeechSynthesisVoice(identifier: "ru-RU")

after synchronizing AVSpeechSynthesisVoice.currentLanguageCode() became "ru" ignoring system language

Here is full code example for Turkish

import UIKit

import AVFoundation

class ViewController: UIViewController {

let synthesizer : AVSpeechSynthesizer = AVSpeechSynthesizer()
var utterance : AVSpeechUtterance = AVSpeechUtterance(string: "")

override func viewDidLoad() {
    super.viewDidLoad()
    UserDefaults.standard.set(["tr"], forKey: "AppleLanguages")
    UserDefaults.standard.synchronize()
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: .interruptSpokenAudioAndMixWithOthers)
    utterance.voice = AVSpeechSynthesisVoice(identifier: "tr-TR")
    synthesizer.pauseSpeaking(at: .word)
    testSpeech()
}

private func testSpeech() {
    utterance = AVSpeechUtterance(string: "Çeviri için deney metni")
    speak()
}

private func speak() {
    if synthesizer.isSpeaking {
        synthesizer.pauseSpeaking(at: .immediate)
        return
    }
    synthesizer.speak(utterance)
}

}