2016年7月24日 星期日

voice recognition demo


Ref : http://code4reference.com/2012/07/tutorial-android-voice-recognition/

main.xml 如下:

按下   speak button  

會啟動voice recognition 的服務  (呼叫  speak ())



=======================================================


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >

    <EditText        android:id="@+id/etTextHint"        android:gravity="top"        android:inputType="textMultiLine"        android:lines="1"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="@string/etSearchHint"/>

    <Button        android:id="@+id/btSpeak"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:onClick="speak"
        android:text="@string/btSpeak"        tools:context=".VoiceRecognitionActivity" />

    <Spinner        android:id="@+id/sNoOfMatches"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:entries="@array/saNoOfMatches"        android:prompt="@string/sNoOfMatches"/>

    <TextView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="@string/tvTextMatches"        android:textStyle="bold" />

    <ListView        android:id="@+id/lvTextMatches"        android:layout_width="match_parent"        android:layout_height="wrap_content" />

</LinearLayout>

========================================================================================
String.xml

========================================================================================

<string name="btSpeak">Speak</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_voice_recognition">Voice Recognition</string>
<string name="tvTextMatches">Text Matches</string>
<string name="sNoOfMatches">No of Matches</string>
<string name="etSearchHint">Speech hint here</string>
<string-array name="saNoOfMatches">
    <item>1</item>
    <item>2</item>
    <item>3</item>
    <item>4</item>
    <item>5</item>
    <item>6</item>
    <item>7</item>
    <item>8</item>
    <item>9</item>
    <item>10</item>
</string-array>

========================================================================================

main.java 如下:


重點是 speak()

會啟動 ACTION_RECOGNIZE_SPEECH 服務
 Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);


//Start the Voice recognizer activity for the result.startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);


最後做完會呼叫 這個   onActivityResult()...是繼承函式

@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {


最後string 會放在 textMatchList  這個ArrayList裡面

========================================================================================


public class MainActivity extends AppCompatActivity {

    private static final int VOICE_RECOGNITION_REQUEST_CODE = 1001;

    private EditText metTextHint;
    private ListView mlvTextMatches;
    private Spinner msTextMatches;
    private Button mbtSpeak;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       // setContentView(R.layout.activity_voice_recognition);        metTextHint = (EditText) findViewById(R.id.etTextHint);
        mlvTextMatches = (ListView) findViewById(R.id.lvTextMatches);
        msTextMatches = (Spinner) findViewById(R.id.sNoOfMatches);
        mbtSpeak = (Button) findViewById(R.id.btSpeak);
        checkVoiceRecognition();
    }

    public void checkVoiceRecognition() {
        // Check if voice recognition is present        PackageManager pm = getPackageManager();
        List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
                RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
        if (activities.size() == 0) {
            mbtSpeak.setEnabled(false);
            mbtSpeak.setText("Voice recognizer not present");
            Toast.makeText(this, "Voice recognizer not present",
                    Toast.LENGTH_SHORT).show();
        }
    }

    public void speak(View view) {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);

        // Specify the calling package to identify your application        intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass()
                .getPackage().getName());

        // Display an hint to the user about what he should say.        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, metTextHint.getText()
                .toString());

        // Given an hint to the recognizer about what the user is going to say        //There are two form of language model available        //1.LANGUAGE_MODEL_WEB_SEARCH : For short phrases        //2.LANGUAGE_MODEL_FREE_FORM  : If not sure about the words or phrases and its domain.
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);

        // If number of Matches is not selected then return show toast message        if (msTextMatches.getSelectedItemPosition() == AdapterView.INVALID_POSITION) {
            Toast.makeText(this, "Please select No. of Matches from spinner",
                    Toast.LENGTH_SHORT).show();
            return;
        }

        int noOfMatches = Integer.parseInt(msTextMatches.getSelectedItem()
                .toString());
        // Specify how many results you want to receive. The results will be        // sorted where the first result is the one with higher confidence.        intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, noOfMatches);
        //Start the Voice recognizer activity for the result.        startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
    }

    @Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == VOICE_RECOGNITION_REQUEST_CODE)

            //If Voice recognition is successful then it returns RESULT_OK            if(resultCode == RESULT_OK) {

                //  把data 從 voice recognition 中取出來
                ArrayList<String> textMatchList = data
                        .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

                if (!textMatchList.isEmpty()) {
                    // If first Match contains the 'search' word                    // Then start web search.                    if (textMatchList.get(0).contains("search")) {

                        String searchQuery = textMatchList.get(0);
                        searchQuery = searchQuery.replace("search","");
                        Intent search = new Intent(Intent.ACTION_WEB_SEARCH);
                        search.putExtra(SearchManager.QUERY, searchQuery);
                        startActivity(search);
                    } else {
                        // populate the Matches                        mlvTextMatches                                .setAdapter(new ArrayAdapter<String>(this,
                                        android.R.layout.simple_list_item_1,
                                        textMatchList));
                    }

                }
                //Result code for various error.            }else if(resultCode == RecognizerIntent.RESULT_AUDIO_ERROR){
                showToastMessage("Audio Error");
            }else if(resultCode == RecognizerIntent.RESULT_CLIENT_ERROR){
                showToastMessage("Client Error");
            }else if(resultCode == RecognizerIntent.RESULT_NETWORK_ERROR){
                showToastMessage("Network Error");
            }else if(resultCode == RecognizerIntent.RESULT_NO_MATCH){
                showToastMessage("No Match");
            }else if(resultCode == RecognizerIntent.RESULT_SERVER_ERROR){
                showToastMessage("Server Error");
            }
        super.onActivityResult(requestCode, resultCode, data);
    }

    void showToastMessage(String message){
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

}




沒有留言:

張貼留言