4

我想使用 iOS 7 新的语音合成 API,我的应用程序本地化为法语和英语。

为此,必须本地化两件事:

  • 语音文本:我把它放在普通文件中,并使用宏localizable.string在代码中检索它。NSLocalizedString

  • 语音语言:AVSpeechSynthesisVoice必须为相应的语言选择。

类实例化方法是AVSpeechSynthesisVoice voiceWithLanguage:(NSString *)lang. 我目前正在[NSLocale currentLocale].localeIdentifier用作此方法的参数。

问题:如果用户的设备语言是葡萄牙语,[NSLocale currentLocale]选择葡萄牙语发音,而解析的文本NSLocalizedString是英语。

我如何知道当前读取的是哪个语言环境NSLocalizedString

4

2 回答 2

5

好的,我终于理解了 Apple API:

  • [NSLocale currentLocale]:不返回用户在设置>常规>国际中选择的当前语言,但返回用户在同一屏幕中选择的区域代码。

  • [NSLocale preferredLanguages]:这个列表确实给出了设备语言,它是这个列表中的第一个字符串

  • [[NSBundle mainBundle] preferredLocalizations]返回由应用程序解析的语言包。我想这就是NSLocalizedString用途。在我的情况下它只有 1 个对象,但我想知道在哪些情况下它可以有多个对象。

  • [AVSpeechSynthesisVoice currentLanguageCode]返回系统预定义的语言代码。

  • [AVSpeechSynthesisVoice voiceWithLanguage:]类实例化方法需要完整的语言代码:带有语言和区域。(例如:将@"en" 传递给它会返回nil 对象,它需要@"en-US" 或@"en-GB"...)

  • [AVSpeechSynthesisVoice currentLanguageCode]给出由操作系统确定的默认语音。

所以这就是我的最终代码的样子

 // current user locale (language & region)
    NSString *voiceLangCode = [AVSpeechSynthesisVoice currentLanguageCode];
    NSString *defaultAppLang = [[[NSBundle mainBundle] preferredLocalizations] firstObject];

    // nil voice will use default system voice
    AVSpeechSynthesisVoice *voice = nil;

    // is default voice language compatible with our application language ?
    if ([voiceLangCode rangeOfString:defaultAppLang].location == NSNotFound) {
        // if not, select voice from application language
        NSString *pickedVoiceLang = nil;
        if ([defaultAppLang isEqualToString:@"en"]) {
            pickedVoiceLang = @"en-US";
        } else {
            pickedVoiceLang = @"fr-FR";
        }
        voice = [AVSpeechSynthesisVoice voiceWithLanguage:pickedVoiceLang];
    }


    AVSpeechUtterance *mySpeech = [[AVSpeechUtterance alloc] initWithString:NSLocalizedString(@"MY_SPEECH_LOCALIZED_KEY", nil)];
    frontPicUtterance.voice = voice;

这样,来自新西兰、澳大利亚、英国或加拿大的用户将获得最符合他通常设置的声音。

于 2014-02-21T14:59:18.643 回答
4

Vinzzz 的回答是一个很好的开始——我已经将它概括为适用于任何语言:

NSString *language = [[[NSBundle mainBundle] preferredLocalizations] objectAtIndex:0];
NSString *voiceLangCode = [AVSpeechSynthesisVoice currentLanguageCode];
if (![voiceLangCode hasPrefix:language]) {
    // the default voice can't speak the language the text is localized to;
    // switch to a compatible voice:
    NSArray *speechVoices = [AVSpeechSynthesisVoice speechVoices];
    for (AVSpeechSynthesisVoice *speechVoice in speechVoices) {
        if ([speechVoice.language hasPrefix:language]) {
            self.voice = speechVoice;
            break;
        }
    }
}
于 2014-05-23T09:54:59.490 回答