Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

呼叫系統內建語音辨識模組:Android 語音搜尋實作教學

編輯:關於 Android 程式設計

需求很單純:在專案中加入語音搜尋功能,讓使用者可以用說的取代打字,提升操作體驗。

為什麼要自己寫一份完整範例

網路上關於語音搜尋的片段程式碼很多,但大多零散,幾乎找不到可以直接貼進專案就跑的完整版本。因此這裡整理出一份可複製即用的 Demo,完整示範「啟動語音辨識 → 接收結果 → 呈現在畫面上」的流程。

整體流程

做法是啟動系統內建的 Intent,把 Action 設為 RecognizerIntent.ACTION_RECOGNIZE_SPEECH,再補上幾個提示參數:

intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
        RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "請開始說話");

辨識結束後,在 onActivityResult 中接收資料。系統回傳的候選結果通常不只一筆,而是依相似度排序的陣列;本範例只取第一筆呈現,實務上你可以依需求讓使用者挑選。

這裡透過 Handler 把資料送回主執行緒再更新 UI。專案中的資料後處理,也多半會放在 Handler 裡進行。

開發時踩到的坑

實作過程中曾遇到語音搜尋後 App 崩潰的情形,最後定位到原因:結果呈現時不要在同一個回呼裡做耗時的運算。把重工作移到背景執行緒,或延後到下一輪訊息迴圈處理,就能避免 ANR 與崩潰。

另外也必須處理「裝置不支援語音辨識」的例外狀況,透過 ActivityNotFoundException 攔下,引導使用者安裝語音搜尋元件。

完整程式碼

public class MainActivity extends Activity {

    private Button btnVoice;
    private TextView tvVoiceResult;
    private static final int VOICE_RECOGNITION_REQUEST_CODE = 123456;

    private Handler jumpHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            tvVoiceResult.setText((String) msg.obj);
        }
    };

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

        btnVoice = (Button) findViewById(R.id.btnVoice);
        tvVoiceResult = (TextView) findViewById(R.id.tvVoiceResult);

        btnVoice.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
                    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                            RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
                    intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "請開始說話");
                    startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
                } catch (ActivityNotFoundException e) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle("語音識別");
                    builder.setMessage("您的手機暫不支援語音搜尋功能,點擊確定下載安裝語音搜尋元件。"
                            + "您也可以在各應用商店搜尋「語音搜尋」進行下載安裝。");
                    builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // 此處可跳轉至下載頁面
                        }
                    });
                    builder.setNegativeButton("取消", null);
                    builder.show();
                }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == VOICE_RECOGNITION_REQUEST_CODE
                && resultCode == MainActivity.RESULT_OK) {
            ArrayList<String> matches =
                    data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
            if (matches != null && matches.size() > 0) {
                Message msg = new Message();
                msg.obj = matches.get(0);
                jumpHandler.sendMessage(msg);
            }
        }
    }
}

實務上的補充

這個做法的最大優點是完全複用系統提供的辨識引擎,不需要自行整合語音模型,也不需要额外申請錄音權限,因為錄音行為發生在系統的辨識 Activity 中。代價則是高度依賴裝置是否安裝對應的語音服務,因此例外處理不可省略。若需要離線辨識或自訂熱詞,才需要考慮改用第三方或自建的語音 SDK。

以上就是 Android 語音模組開發的一個完整小範例,有需要的朋友可以直接取用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved