要實現Android平臺的語音識別功能,可以使用Android提供的語音識別API,具體步驟如下:
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.INTERNET" />
<Button
android:id="@+id/btn_speech_to_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="開始語音識別" />
import android.content.Intent;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private static final int SPEECH_REQUEST_CODE = 100;
private Button btnSpeechToText;
private SpeechRecognizer speechRecognizer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSpeechToText = findViewById(R.id.btn_speech_to_text);
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
btnSpeechToText.setOnClickListener(v -> {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
startActivityForResult(intent, SPEECH_REQUEST_CODE);
});
speechRecognizer.setRecognitionListener(new RecognitionListener() {
@Override
public void onReadyForSpeech(Bundle params) {
// 當語音識別引擎準備好接收語音輸入時回調
}
@Override
public void onBeginningOfSpeech() {
// 當用戶開始說話時回調
}
@Override
public void onRmsChanged(float rmsdB) {
// 當音量變化時回調
}
@Override
public void onPartialResults(Bundle partialResults) {
// 在識別過程中返回部分識別結果時回調
}
@Override
public void onResults(Bundle results) {
// 識別完成后返回最終結果時回調
ArrayList<String> speechResults = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if (speechResults != null && !speechResults.isEmpty()) {
String recognizedText = speechResults.get(0);
// 處理識別結果
}
}
@Override
public void onError(int error) {
// 在識別過程中發生錯誤時回調
}
@Override
public void onEndOfSpeech() {
// 當用戶停止說話時回調
}
@Override
public void onEvent(int eventType, Bundle params) {
// 其他事件回調
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
speechRecognizer.destroy();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SPEECH_REQUEST_CODE && resultCode == RESULT_OK) {
ArrayList<String> speechResults = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (speechResults != null && !speechResults.isEmpty()) {
String recognizedText = speechResults.get(0);
// 處理識別結果
}
}
}
}
以上就是實現Android語音識別功能的基本步驟。具體的處理識別結果的邏輯可以根據實際需求進行自定義。