2011-10-25

在 Android 使用語音辨識

本範例在 Android Emulator 無法運作,原因在 Emulator 沒有安裝語音辨識套件,試著安裝 Google Voice Search(內含所需的套件)到 Emulator,但失敗了;再試著安裝 Android Market,想透過 Market 來下載 Voice Search,好不容易 Market 裝好了,但怎麼也找不到 Voice Search,又一殘念!

還是附上程式做紀錄。
public class Speech2TextActivity extends Activity implements OnClickListener {

    private static final int S2T_RESULT_CODE = 1116;
    private static final String TAG = "Speech2TextActivity";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ((Button) this.findViewById(R.id.btn)).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() != R.id.btn) {
            return;
        }
        // 檢查是否支援語音辨識
        PackageManager pm = this.getPackageManager();
        List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
                RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
        if (activities.size() == 0) {
            Log.e(TAG, "Oops...ACTION_RECOGNIZE_SPEECH not present");
            return;
        }
        // 啟動語音辨識
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "請說...");
        this.startActivityForResult(intent, S2T_RESULT_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode != S2T_RESULT_CODE) {
            Log.d(TAG, "The request code doesn't match - " + requestCode);
            return;
        }
        if (resultCode != RESULT_OK) {
            Log.d(TAG, "The result code doesn't match - " + resultCode);
            return;
        }
        // 語音辨識成功後,將結果回寫
        List<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
        TextView tv = (TextView) this.findViewById(R.id.tv);
        tv.setText(result.toString());
    }
}
UI 設定:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
    <Button  
        android:id="@+id/btn"
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:text="Speech 2 Text"
      />
    <TextView  
        android:id="@+id/tv"
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      />
</LinearLayout>

2 則留言: