提问人:J_CHAN0429 提问时间:10/31/2023 更新时间:10/31/2023 访问量:14
语音识别不适用于使用 SpeechRecognizer 即服务的 Android 应用
Speech recognition not working for android app using SpeechRecognizer as a service
问:
只是前言,我是 Android Studio 的全新手,并且总体上是 Java 初学者,但我正在努力制作一个类似 android“siri”的应用程序,我可以说一个短语,手机会自动拾取该短语并输入到应用程序中我说的任何内容。
为此,我选择将语音识别器作为后台服务运行。
在 MainActivity 中激活服务
disable.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View disable) {
Intent start_action = new Intent(MainActivity.this, BackgroundProcess.class);
startService(start_action);
}
后台进程代码
package com.ia;
import static android.app.PendingIntent.getActivity;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.speech.RecognizerIntent;
import android.speech.RecognitionListener;
import android.speech.SpeechRecognizer;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public class BackgroundProcess extends Service implements RecognitionListener{
private static final int REQUEST_CODE_SPEECH_INPUT = 1000;
private SpeechRecognizer speechRecognizer;
private int speak() {
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(getApplicationContext());
speechRecognizer.setRecognitionListener(this);
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass()
.getPackage().getName());
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 10);
speechRecognizer.startListening(intent);
return START_REDELIVER_INTENT;
}
@Override
public void onCreate() {
speak();
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onReadyForSpeech(Bundle bundle) {
}
@Override
public void onBeginningOfSpeech() {
}
@Override
public void onRmsChanged(float v) {
}
@Override
public void onBufferReceived(byte[] bytes) {
}
@Override
public void onEndOfSpeech() {
}
@Override
public void onError(int i) {
}
@Override
public void onResults(Bundle results) {
ArrayList resultList = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
for (int i=0;i < resultList.size();i++){
Log.d("speech", "result = " + resultList.get(i).toString());
Toast.makeText(this, "Hello.", Toast.LENGTH_LONG).show();
}
}
@Override
public void onPartialResults(Bundle bundle) {
}
@Override
public void onEvent(int i, Bundle bundle) {
}
}
答: 暂无答案
评论