Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 初級開發 >> Android 輕松實現語音識別

Android 輕松實現語音識別

編輯:初級開發

Android 輕松實現語音識別完整代碼如下:package com.example.android.apis.app;import com.example.android.apis.R;import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.VIEw;
import android.view.VIEw.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListVIEw;import Java.util.ArrayList;
import Java.util.List;
public
class VoiceRecognition extends Activity implements OnClickListener {     private
static
final
int VOICE_RECOGNITION_REQUEST_CODE =
1234;     private ListVIEw mList;     
    @Override
    public
void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);         // Inflate our UI from its XML layout description.
        setContentVIEw(R.layout.voice_recognition);         // Get display items for later interaction
        Button speakButton = (Button) findViewById(R.id.btn_speak);         mList = (ListView) findVIEwById(R.id.list);         // Check to see if a recognition activity is present
        PackageManager pm = getPackageManager();
        List<ResolveInfo> activities = pm.queryIntentActivitIEs(
                new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
        if (activitIEs.size() !=
0) {
            speakButton.setOnClickListener(this);
        } else {
            speakButton.setEnabled(false);
            speakButton.setText("Recognizer not present");     }    
public
void onClick(VIEw v) {
        if (v.getId() == R.id.btn_speak) {
            startVoiceRecognitionActivity();     }    
private
void startVoiceRecognitionActivity() {
        Intent intent =
new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech recognition demo");
        startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);     @Override
    protected
void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
            // Fill the list vIEw with the strings the recognizer thought it could have heard
            ArrayList<String> matches = data.getStringArrayListExtra(
                    RecognizerIntent.EXTRA_RESULTS);
            mList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
                    matches));
        }         super.onActivityResult(requestCode, resultCode, data); }
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved