Android Speech To Text(STT) 建國科技大學 資管系 饒瑞佶 2017/10 V1
語音轉文字 Speech To Text 透過Google的雲端服務,所以需要開啟網路 可以讓使用者透過語音控制
UI Design
<RelativeLayout xmlns:android="http://schemas. android xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent"> <ScrollView android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_above="@+id/btnSpeakContainer" android:layout_alignParentTop="true" android:layout_marginBottom="20dp" android:padding="20dp"> <TextView android:id="@+id/voiceInput" android:forceHasOverlappingRendering="true" android:textAppearance="@style/TextAppearance.AppCompat.Medium" /> </ScrollView> 用來顯示語音轉文字的結果
點選麥克風開始說話 <LinearLayout android:id="@+id/btnSpeakContainer" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:background="#f5f5f5" android:gravity="center_horizontal" android:orientation="vertical" android:padding="20dp"> <ImageButton android:id="@+id/btnSpeak" android:layout_width="wrap_content" android:background="@null" android:padding="16dp" android:scaleType="fitCenter" android:src="@mipmap/ic_microphone_2" /> <TextView android:id="@+id/textView" android:layout_below="@id/btnSpeak" android:layout_margin="10dp" android:text="請點麥克風並開始說話" /> </LinearLayout> </RelativeLayout> 點選麥克風開始說話
result
Code
// 設定取得語音服務 private static final int REQ_CODE_SPEECH_INPUT = 100; // 回傳結果textview private TextView mVoiceInputTv; // 麥克風按鈕 private ImageButton mSpeakBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mVoiceInputTv = (TextView) findViewById(R.id.voiceInput); mSpeakBtn = (ImageButton) findViewById(R.id.btnSpeak); mSpeakBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { startVoiceInput(); // 開始講話並辨識 } });
private void startVoiceInput() { 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()); intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "您好,請開始說話!"); try { startActivityForResult(intent, REQ_CODE_SPEECH_INPUT); // 取得結果 } catch (ActivityNotFoundException a) { }
// 處理Intent回傳結果 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQ_CODE_SPEECH_INPUT: { if (resultCode == RESULT_OK && null != data) { ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); mVoiceInputTv.setText(result.get(0)); } break;