Provide a Java code example using Android API `RecognizerIntent.EXTRA_BIASING_STRINGS`.
Mar 3, 9:33pm

Here’s a concise Java code example demonstrating how to use RecognizerIntent.EXTRA_BIASING_STRINGS in an Android app. This feature allows you to provide a list of strings to bias the speech recognition results toward specific words or phrases.


Example: Using RecognizerIntent.EXTRA_BIASING_STRINGS

java
import android.content.Intent;
import android.speech.RecognizerIntent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private static final int SPEECH_REQUEST_CODE = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Start speech recognition with biasing strings
        startSpeechRecognition();
    }

    private void startSpeechRecognition() {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);

        // Add biasing strings to improve recognition accuracy for specific words
        ArrayList<String> biasingStrings = new ArrayList<>();
        biasingStrings.add("coffee");
        biasingStrings.add("tea");
        biasingStrings.add("latte");
        biasingStrings.add("espresso");
        intent.putStringArrayListExtra(
                RecognizerIntent.EXTRA_BIASING_STRINGS,
                biasingStrings);

        // Optional: Set a hint for the user
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Say something...");

        startActivityForResult(intent, SPEECH_REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == SPEECH_REQUEST_CODE && resultCode == RESULT_OK) {
            ArrayList<String> results = data.getStringArrayListExtra(
                    RecognizerIntent.EXTRA_RESULTS);
            if (results != null && !results.isEmpty()) {
                String spokenText = results.get(0);
                // Handle the recognized text
            }
        }
    }
}

Key Points

  • EXTRA_BIASING_STRINGS: This extra allows you to provide a list of words or phrases that the recognizer should prioritize.
  • Use Case: Useful for apps where you expect specific commands or vocabulary (e.g., voice-controlled menus, custom voice assistants).
  • Compatibility: Ensure the device supports RecognizerIntent.ACTION_RECOGNIZE_SPEECH and the biasing feature.

Mar 3, 9:33pm

This is a shared conversation and may include unverified content that doesn't reflect Mistral AI's views. Login to resume chatting.

Le Chat can make mistakes. Check answers. Learn more