Android Studio实现Java语音控制手电筒功能求助
实现Android手电筒的语音控制功能
1. 补充必要权限
首先确保AndroidManifest.xml中添加语音录制和相机相关权限:
<!-- 语音录制权限 --> <uses-permission android:name="android.permission.RECORD_AUDIO" /> <!-- 手电筒相关权限 --> <uses-permission android:name="android.permission.CAMERA" /> <uses-feature android:name="android.hardware.camera" /> <uses-feature android:name="android.hardware.camera.flash" />
2. 整合语音识别逻辑到现有代码
在你的SecondActivity中添加语音识别相关代码,以下是完整整合示例:
import android.content.Intent; import android.speech.RecognitionListener; import android.speech.RecognizerIntent; import android.speech.SpeechRecognizer; import android.widget.Button; import android.widget.CompoundButton; import android.widget.Switch; import android.widget.TextView; import android.hardware.camera2.CameraAccessException; import android.hardware.camera2.CameraManager; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import java.util.ArrayList; import java.util.Locale; public class SecondActivity extends AppCompatActivity { private Switch aSwitch; private TextView textView; private CameraManager cameraManager; private String cameraID; private String result; private SpeechRecognizer speechRecognizer; private Button voiceControlBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); aSwitch = findViewById(R.id.switch_torch); textView = findViewById(R.id.text_status); voiceControlBtn = findViewById(R.id.btn_voice_control); // 初始化语音识别 initSpeechRecognizer(); // 开关控制逻辑 aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { torch(isChecked); } }); // 语音控制按钮点击事件 voiceControlBtn.setOnClickListener(v -> startVoiceRecognition()); } private void initSpeechRecognizer() { if (!SpeechRecognizer.isRecognitionAvailable(this)) { textView.setText("语音识别服务不可用"); return; } speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this); speechRecognizer.setRecognitionListener(new RecognitionListener() { @Override public void onReadyForSpeech(Bundle params) { textView.setText("请说出指令..."); } @Override public void onBeginningOfSpeech() {} @Override public void onRmsChanged(float rmsdB) {} @Override public void onBufferReceived(byte[] buffer) {} @Override public void onEndOfSpeech() {} @Override public void onError(int error) { String errorMsg = switch (error) { case SpeechRecognizer.ERROR_AUDIO -> "音频错误"; case SpeechRecognizer.ERROR_CLIENT -> "客户端错误"; case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS -> "权限不足"; case SpeechRecognizer.ERROR_NETWORK -> "网络错误"; case SpeechRecognizer.ERROR_NETWORK_TIMEOUT -> "网络超时"; case SpeechRecognizer.ERROR_NO_MATCH -> "未匹配到指令"; case SpeechRecognizer.ERROR_RECOGNIZER_BUSY -> "识别器忙碌"; case SpeechRecognizer.ERROR_SERVER -> "服务端错误"; case SpeechRecognizer.ERROR_SPEECH_TIMEOUT -> "语音超时"; default -> "未知错误"; }; textView.setText("识别失败:" + errorMsg); } @Override public void onResults(Bundle results) { ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION); if (matches != null && !matches.isEmpty()) { String command = matches.get(0).toLowerCase(Locale.ENGLISH); if (command.contains("turn on the flash light")) { torch(true); aSwitch.setChecked(true); } else if (command.contains("turn off the flash light")) { torch(false); aSwitch.setChecked(false); } else { textView.setText("未识别到有效指令:" + command); } } } @Override public void onPartialResults(Bundle partialResults) {} @Override public void onEvent(int eventType, Bundle params) {} }); } private void startVoiceRecognition() { 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.ENGLISH); intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "请说出手电筒控制指令"); speechRecognizer.startListening(intent); } private void torch(boolean isChecked) { try { cameraManager = (CameraManager) getSystemService(CAMERA_SERVICE); cameraID = cameraManager.getCameraIdList()[0]; cameraManager.setTorchMode(cameraID, isChecked); result = isChecked ? "ON" : "OFF"; textView.setText("手电筒状态:" + result); } catch (CameraAccessException e) { e.printStackTrace(); textView.setText("操作失败:" + e.getMessage()); } } @Override protected void onDestroy() { super.onDestroy(); if (speechRecognizer != null) { speechRecognizer.destroy(); } } }
3. 布局补充(activity_second.xml)
需要在布局中添加语音控制按钮:
<Button android:id="@+id/btn_voice_control" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="语音控制" android:layout_marginTop="20dp"/>
关键注意事项
- 运行前需授予录音权限和相机权限,若targetSdkVersion >= 23,需在代码中动态申请权限
- 部分设备可能无内置语音识别服务,可提示用户安装Google语音识别服务
- 指令匹配使用
contains提升容错率,也可根据需求调整为精确匹配
内容的提问来源于stack exchange,提问作者clarkchuni
相关产品推荐
相关产品推荐

