1

在我的应用程序中,我想让用户有机会通过语音命令(例如通过 Cortana)打开和关闭灯。我了解 VCD 概念并且非常喜欢,但我不知道如何在我的代码中处理不同的语言。

鉴于我有两种语言(英语和德语):

<CommandSet xml:lang="en" Name="LightSwitch_en">
    <CommandPrefix>Switch the light</CommandPrefix>
    <Example>Switch the light on.</Example>
    <Command Name="switchLight">
        <Example>on</Example>
        <ListenFor>{status}</ListenFor>
        <Feedback>Light will be switched {status}.</Feedback>
        <Navigate />
    </Command>
    <PhraseList Label="status">
        <Item>on</Item>
        <Item>off</Item>
    </PhraseList>        
</CommandSet>

<CommandSet xml:lang="de" Name="LightSwitch_de">
    <CommandPrefix>Schalte das licht</CommandPrefix>
    <Example>Schalte das Licht ein.</Example>
    <Command Name="switchLight">
        <Example>ein</Example>
        <ListenFor>{status}</ListenFor>
        <Feedback>Licht wird {status}geschaltet.</Feedback>
        <Navigate />
    </Command>
    <PhraseList Label="status">
        <Item>ein</Item>
        <Item>aus</Item>
    </PhraseList>        
</CommandSet>

当我的应用程序通过语音命令启动时,我可以轻松提取口语并访问status参数。但是因为它是一个字符串,所以我会根据用户说的语言得到不同的结果。

因此,如果用户说英语,则字符串为"on",但如果他说德语,则字符串为"ein"。那么我怎么知道我需要在我的应用程序中监听哪个字符串?我的目标是这样的:

if (arg.Equals("on"))
    Light.On();
else if (arg.Equals("off"))
    Light.Off();

但这仅适用于英语,而不适用于德语。我讨厌检查所有语言中的所有不同字符串,这不是正确的方法。<Item>不幸的是,由于它们只是字符串,因此也不可能给标签一个额外的属性。

我可以做类似的事情,if (arg.Equals("on") || arg.Equals("ein")) Light.On();但正如你所看到的,这真的很丑陋,每次我改变一些东西时我都必须调整它,好吧,想象一下我有大约 15 种语言要检查......

您知道更智能的解决方案吗?

4

2 回答 2

2

由于 Cortana 将使用与内置应用程序本地化方法相同的本地化方法,您能否不将所有字符串放入资源文件中,然后将返回的字符串与本地化资源进行比较?

于 2015-11-25T15:10:49.300 回答
2

如果您只需要解决该特定情况,您可以执行以下操作,而不是一个列表,只需为每种语言定义两个命令:

 <Command Name="oncommand" >
    <Example>switch on</Example>
    <ListenFor>switch on</ListenFor>
    <Feedback>Light will be switched on.</Feedback>
    <Navigate />
</Command>

<Command Name="offcommand">
    <Example>switch off</Example>
    <ListenFor>switch off</ListenFor>
    <Feedback>Light will be switched off.</Feedback>
    <Navigate />
</Command>

然后在代码中检测调用了什么命令:

if (args.Kind == ActivationKind.VoiceCommand)
        {
            var commandArgs = args as VoiceCommandActivatedEventArgs;
            var speechRecognitionResult = commandArgs.Result;
            string voiceCommandName = speechRecognitionResult.RulePath.First();
            string textSpoken = speechRecognitionResult.Text;
            return voiceCommandName;
        }

其中 voiceCommandName 是“oncommand”或“offcommand”。

于 2015-11-25T21:32:52.837 回答