Giới thiệu
Ví dụ này minh họa cách sử dụng SpeechRecognizer (qua RecognizerIntent) để nhận diện giọng nói người dùng và so khớp với đáp án đúng.
Bước 1: Tạo dự án mới
Tạo project Android Studio: File → New Project.
Bước 2: Layout (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16sp"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:textSize="16sp"
android:textStyle="bold" />
</LinearLayout>
Bước 3: MainActivity - Khởi động nhận diện giọng nói
Sử dụng RecognizerIntent.ACTION_RECOGNIZE_SPEECH với LANGUAGE_MODEL_FREE_FORM và prompt tùy chỉnh. Xử lý kết quả trong onActivityResult.
package app.com.sample;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.widget.TextView;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private final int REQUEST_SPEECH_RECOGNIZER = 3000;
private TextView textView;
private final String mQuestion = "Công ty nào là nhà bán lẻ trực tuyến lớn nhất hành tinh?";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
startSpeechRecognizer();
}
private void startSpeechRecognizer() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, mQuestion);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "vi-VN"); // Thêm: đặt ngôn ngữ tiếng Việt
startActivityForResult(intent, REQUEST_SPEECH_RECOGNIZER);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_SPEECH_RECOGNIZER) {
if (resultCode == RESULT_OK) {
List results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
String mAnswer = results.get(0);
if (mAnswer.toUpperCase().contains("AMAZON")) {
textView.setText(String.format("\n\nCâu hỏi: %s\n\nTrả lời của bạn: '%s' - Chính xác!", mQuestion, mAnswer));
} else {
textView.setText(String.format("\n\nCâu hỏi: %s\n\nTrả lời của bạn: '%s' - Sai!", mQuestion, mAnswer));
}
}
}
}
}
Bước 4: Manifest - Quyền RECORD_AUDIO
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
</manifest>
Chạy ứng dụng
Chạy app, dialog nhận diện giọng nói hiện ra với câu hỏi. Nói "Amazon" (hoặc "A-ma-zông") sẽ hiện kết quả chính xác.
Mở rộng: SpeechRecognizer class (không dùng system dialog)
Để tùy chỉnh UI hoàn toàn (không dùng dialog hệ thống), dùng class android.speech.SpeechRecognizer:
SpeechRecognizer recognizer = SpeechRecognizer.createSpeechRecognizer(this);
recognizer.setRecognitionListener(new RecognitionListener() {
@Override public void onResults(Bundle results) {
ArrayList matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
// Xử lý matches.get(0)...
}
// Implement các method khác...
});
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "vi-VN");
recognizer.startListening(intent);
// Nhớ gọi recognizer.destroy() khi không dùng nữa.
Lưu ý
- Yêu cầu kết nối internet (Google Speech-to-Text cloud).
- Cần xin quyền
RECORD_AUDIOruntime (API 23+). - Ngôn ngữ hỗ trợ: "vi-VN", "en-US", "ja-JP", v.v. Xem
RecognizerIntent.EXTRA_LANGUAGE. - Trên Android 12+, có thể dùng
SpeechRecognizer.OnDeviceSpeechRecognizercho nhận diện offline (nếu thiết bị hỗ trợ).