Android 內建了語音轉文字的能力,只要透過 Intent 呼叫系統的 RecognizerIntent,就能在幾行程式碼內完成語音輸入,不必自己訓練模型。
在 manifest 中加入必要權限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/txtVoiceInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="@string/sensor_voice_input_lb_title" >
<requestFocus />
</EditText>
<Button
android:id="@+id/btnStartVoiceInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/sensor_voice_input_btn_startinput" />
</LinearLayout>
private Button btnStartVoiceInput;
private EditText txtVoiceInput;
private int InputResultCode = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sensor_voice_input);
txtVoiceInput = (EditText) findViewById(R.id.txtVoiceInput);
btnStartVoiceInput = (Button) findViewById(R.id.btnStartVoiceInput);
btnStartVoiceInput.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 呼叫系統語音輸入 API
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
// 必須指定語言模式
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
try {
startActivityForResult(intent, InputResultCode);
txtVoiceInput.setText("");
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(),
"抱歉,您的系統不支援語音識別輸入。", Toast.LENGTH_LONG);
t.show();
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == InputResultCode && resultCode == RESULT_OK && data != null) {
// 取得解析結果
ArrayList<String> voiceList = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtVoiceInput.setText(voiceList.get(0));
}
}
Android 語音轉文字的關鍵在 android.speech 套件與 RecognizerIntent 類別。我們觸發一個 Intent 讓系統跳出對話框進行識別,該 Activity 負責把語音轉成文字,再把結果回傳給呼叫方。因為需要接收結果,所以必須用 startActivityForResult() 而非 startActivity()。
呼叫時一定要透過 putExtra() 提供 RecognizerIntent.EXTRA_LANGUAGE_MODEL,本例設為 en-US;實作中文輸入時可改為 zh-TW 或中文語系代碼。
結果會以 RecognizerIntent.EXTRA_RESULTS 為 key,用 ArrayList 形式回傳,且僅在 resultCode 為 RESULT_OK 時有效。候選字通常有多個,取第 0 筆是最佳猜測,若要提供挑選介面,可把整個 list 呈現給使用者。
最後要留意相容性:在不支援語音 API 的機型或版本上,startActivityForResult 會丟出 ActivityNotFoundException,因此必須像範例那樣捕捉並提示使用者。
更多 Android 相關資訊見 Android 專題頁面。