2014-02-21 32 views
2

我想使用iOS 7新语音合成API,并且我的应用程序已在本地化为法语&英文。Speach Synthezis API:NSLocalizedString使用哪种语言环境?

对于这项工作,两件事情必须要本地化:

  • 演讲全文:我把它放在平常localizable.string文件,并使用NSLocalizedString宏代码检索。

  • 演讲语言:AVSpeechSynthesisVoice必须选择相应的语言。

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

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

如何知道NSLocalizedString当前正在读取哪个区域?

回答

2

好吧,我终于成功地让苹果的API的意义:

  • [NSLocale currentLocale]:不返回设置由用户挑选当前语言>常规>国际化,而是返回由用户在选定的区域码同一屏幕。

  • [NSLocale preferredLanguages]:此列表确实给设备的语言,它在这个名单

  • [[NSBundle mainBundle] preferredLocalizations]回报语言包,通过应用程序解决了第一个字符串。我想这是NSLocalizedString使用。在我的例子中它只有1个对象,但我想知道在哪些情况下可以有多个对象。

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

  • [AVSpeechSynthesisVoice voiceWithLanguage:] class instanciation方法需要完整的语言代码:带语言和区域。 (例如:传递@“en”到它将返回零对象,它需要@“en-US”或@“en-GB”...)

  • [AVSpeechSynthesisVoice currentLanguageCode]给出默认语音,由OS决定。

所以这是我的最终代码看起来像

// 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; 

这样,来自新西兰,澳大利亚,GreatBritain,或加拿大用户将获得对应最让他平时设置的声音。

+0

我认为[NSLocale preferredLanguages]比较好,因为塔的应用程序可能会不本地化异国语言,但TTS可在设备上使用 – djdance

3

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; 
     } 
    } 
}