萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android 語音識別整合指南:RecognizerIntent 雲端識別、權限、離線模式與 UI 交互

Android 系統內建 Google 語音識別服務,通過 RecognizerIntent 即可調用雲端 ASR 引擎,無需接入第三方 SDK。本文詳細講解啟動識別流程、結果處理、權限配置、離線語音包下載、自定義 UI 彈窗與常見錯誤碼處理。

一、核心流程圖解

  1. 檢查設備是否支援語音識別 PackageManager.queryIntentActivities
  2. 構建 RecognizerIntent.ACTION_RECOGNIZE_SPEECH Intent
  3. 配置語言模型、提示語、最大結果數
  4. startActivityForResult 啟動系統識別界面
  5. onActivityResult 接收 EXTRA_RESULTS 列表

二、完整 Activity 實現

public class VoiceRecognitionActivity extends AppCompatActivity implements View.OnClickListener {
    private static final int REQ_VOICE = 1234;
    private ListView lvResults;
    private Button btnSpeak;

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

        lvResults = findViewById(R.id.lv_results);
        btnSpeak = findViewById(R.id.btn_speak);
        btnSpeak.setOnClickListener(this);

        // 檢查識別服務是否可用
        PackageManager pm = getPackageManager();
        List activities = pm.queryIntentActivities(
            new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
        if (activities.isEmpty()) {
            btnSpeak.setEnabled(false);
            btnSpeak.setText("語音識別不可用");
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_speak) {
            startVoiceRecognition();
        }
    }

    private void startVoiceRecognition() {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
            RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault().toString());
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "請說話...");
        intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 5);
        intent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true); // 實時部分結果
        startActivityForResult(intent, REQ_VOICE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQ_VOICE && resultCode == RESULT_OK) {
            ArrayList matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
            lvResults.setAdapter(new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1, matches));
        } else if (resultCode == RecognizerIntent.RESULT_AUDIO_ERROR) {
            Toast.makeText(this, "音頻錄製錯誤", Toast.LENGTH_SHORT).show();
        } else if (resultCode == RecognizerIntent.RESULT_NETWORK_ERROR) {
            Toast.makeText(this, "網絡不可用", Toast.LENGTH_SHORT).show();
        } else if (resultCode == RecognizerIntent.RESULT_NO_MATCH) {
            Toast.makeText(this, "未識別到語音", Toast.LENGTH_SHORT).show();
        }
    }
}

三、佈局文件

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">
    <Button android:id="@+id/btn_speak"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="開始語音識別" />
    <ListView android:id="@+id/lv_results"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:layout_marginTop="16dp" />
</LinearLayout>

四、進階主題

1. 離線語音識別

用戶需在「設置 → 語言與輸入法 → Google 語音輸入 → 離線語音識別」下載語言包。App 可引導用戶:

Intent intent = new Intent(Settings.ACTION_VOICE_INPUT_SETTINGS);
startActivity(intent);

2. 自定義識別 UI (不使用系統彈窗)

使用 SpeechRecognizer 類直接控制識別會話,需自行處理音頻錄製、音量可視化、錯誤恢復,適合深度定製場景。

3. 隱私合規

  • 聲明 RECORD_AUDIO 權限 (API 23+ 動態申請)。
  • 隱私政策說明語音數據上傳 Google 服務器。
  • 提供「不使用語音功能」選項。

4. 常見錯誤碼對照

錯誤碼常量原因
1RESULT_NETWORK_ERROR網絡不可用
2RESULT_AUDIO_ERROR音頻錄製失敗
3RESULT_SERVER_ERROR服務端錯誤
4RESULT_CLIENT_ERROR客戶端參數錯誤
5RESULT_NO_MATCH無識別結果
6RESULT_RECOGNIZER_BUSY引擎忙碌

善用系統內建語音識別,可零成本為 App 增加語音輸入、語音控制、智能助手等 AI 體驗。

copyright © 萬盛學電腦網 all rights reserved