[SOLVED] Swift – how to get the text to speech languages as descriptive string

Issue

I’m trying to get the text to speech language codes (in BCP 47) to transform into a descriptive string for selecting the language to have text to speech feature in the app.

Expected –

Arabic (Saudi Arabia) – ar-SA
Chinese (China) – zh-CN
Chinese (Hong Kong SAR China) – zh-HK
Chinese (Taiwan) – zh-TW
Czech (Czech Republic) – cs-CZ

Actual –

ar-SA (fixed)
cs-CZ (fixed)

class func getListOfSupportedLanguages() {
        for voice in (AVSpeechSynthesisVoice.speechVoices()){
            print(voice.language)
            let language = Locale.init(identifier: voice.language)
            print(language.description)
        }
    }

I’m following this helpful website and got different results.

https://useyourloaf.com/blog/synthesized-speech-from-text/

@property (strong, nonatomic) NSArray *languageCodes;
@property (strong, nonatomic) NSDictionary *languageDictionary;
@property (strong, nonatomic) AVSpeechSynthesizer *synthesizer;

- (NSArray *)languageCodes
{
    if (!_languageCodes)
    {
        _languageCodes = [self.languageDictionary keysSortedByValueUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    }
    return _languageCodes;
}

// Map between language codes and locale specific display name
- (NSDictionary *)languageDictionary
{
    if (!_languageDictionary)
    {
        NSArray *voices = [AVSpeechSynthesisVoice speechVoices];
        NSArray *languages = [voices valueForKey:@"language"];

        NSLocale *currentLocale = [NSLocale autoupdatingCurrentLocale];
        NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
        for (NSString *code in languages)
        {
            dictionary[code] = [currentLocale displayNameForKey:NSLocaleIdentifier value:code];
        }
        _languageDictionary = dictionary;
    }
    return _languageDictionary;
}

Solution

I got it working, thanks to Matt – NSLocale has displayName and the Locale doesn’t have one. According to the posting below

NSLocale Swift 3

Here is the code –

   class func getListOfSupportedLanguages() {
         let current = Locale.current.languageCode

         for voice in (AVSpeechSynthesisVoice.speechVoices()){
              let language = NSLocale.init(localeIdentifier: current!)
              print(language.displayName(forKey: NSLocale.Key.identifier, value: voice.language)?.description as! String)
         }
   }

the output –

English (Australia)
English (United Kingdom)
English (Ireland)
English (United States)
English (South Africa)

Answered By – Meep

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.