Google 云语音 API 添加 SpeechContext

Google Cloud Speech API add SpeechContext

我想在我的应用程序中添加一些关键字,以便 API 可以更有效地识别口语。 例如 Im having trouble recognizing the some Italian words that starts with E ,(E` per me) 例如。或者用德语 (er geht)。

这是我的代码:

public void recognize (int sampleRate) {
    if (mApi == null) {
        Log.w(TAG, "API not ready. Ignoring the request.");
        return;
    }
    // Configure the API
    mRequestObserver = mApi.streamingRecognize(mResponseObserver);
    mRequestObserver.onNext(StreamingRecognizeRequest.newBuilder()
            .setStreamingConfig(StreamingRecognitionConfig.newBuilder()
                    .setConfig(RecognitionConfig.newBuilder()
                            .setLanguageCode(getDefaultLanguageCode())
                            .setEncoding(RecognitionConfig.AudioEncoding.LINEAR16)
                            .setSampleRateHertz(sampleRate)
                            .build())
                    .setInterimResults(true)
                    .setSingleUtterance(true)
                    .build())
            .build());
}

为不同的情况设置语言:

private String getDefaultLanguageCode() {

    SharedPreferences getLangSharedPrefs = getSharedPreferences("langSelected",0);
    String selectedLanguage = getLangSharedPrefs.getString("langSelected", null);
    switch (selectedLanguage) {
        case "German":
            langaugeCode = "de-DE";
            break;
        case "Italian":
            langaugeCode = "it-IT";
            break;
        case "Spanish" :
            langaugeCode = "es-ES";
            break;
        case "French" :
            langaugeCode = "fr-FR";
            break;
    }
    return langaugeCode;
}

我找到了解决方案:

 public void startRecognizing(int sampleRate) {
    if (mApi == null) {
        Log.w(TAG, "API not ready. Ignoring the request.");
        return;
    }
    // Configure the API
    mRequestObserver = mApi.streamingRecognize(mResponseObserver);
    SpeechContext.Builder speechBuilder = SpeechContext.newBuilder();
    speechBuilder.addPhrases("E per me");
    speechBuilder.addPhrases("E");
    mRequestObserver.onNext(StreamingRecognizeRequest.newBuilder()
            .setStreamingConfig(StreamingRecognitionConfig.newBuilder()
                    .setConfig(RecognitionConfig.newBuilder()
                            .setLanguageCode(getDefaultLanguageCode())
                            .setEncoding(RecognitionConfig.AudioEncoding.LINEAR16)
                            .setSampleRateHertz(sampleRate)
                            .addSpeechContexts(speechBuilder)
                            .build())
                    .setInterimResults(true)
                    .setSingleUtterance(true)
                    .build())
            .build());
}