要将EditText的文本输入与语音识别结合起来,你可以使用Android的SpeechRecognizer
类。以下是一个简单的示例,展示了如何实现这个功能:
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.INTERNET" />
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入文本或说出你想说的话" />
<Button
android:id="@+id/button_speech_recognition"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="语音识别" />
</LinearLayout>
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private EditText editText;
private Button buttonSpeechRecognition;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editText);
buttonSpeechRecognition = findViewById(R.id.button_speech_recognition);
buttonSpeechRecognition.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startSpeechRecognition();
}
});
}
private void startSpeechRecognition() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass().getPackage().getName());
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, REQUEST_CODE_SPEECH_RECOGNITION);
} else {
Toast.makeText(this, "无法识别语音,请确保设备支持语音识别", Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_SPEECH_RECOGNITION && resultCode == RESULT_OK) {
ArrayList<String> results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (!results.isEmpty()) {
editText.setText(results.get(0));
}
}
}
}
这个示例中,当用户点击"语音识别"按钮时,会启动系统自带的语音识别功能。识别结果会显示在EditText中。请注意,这个示例仅适用于支持语音识别的设备。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。