我正在使用 Android语音识别服务来收听用户的语音。该服务不断在后台运行,一旦收到信号(例如按下按钮),我就会向服务发送一条消息,打开麦克风,服务开始监听接下来的5秒钟。
protected final Messenger mServerMessenger = new Messenger(new IncomingHandler(this));
之后它会停止收听,直到它再次收到信号。它与here基本相同,但效果非常好。
但我想在麦克风打开时添加“Beep” - 声音。我以为语音识别课会自动发出哔哔声?因此我不想加载额外的“beep”-mp3,而是使用内置函数。
你能告诉我,如何激活“哔”声?
public class VoiceCommandService extends Service {
protected AudioManager mAudioManager;
protected SpeechRecognizer mSpeechRecognizer;
protected Intent mSpeechRecognizerIntent;
protected final Messenger mServerMessenger = new Messenger(new IncomingHandler(this));
protected boolean mIsListening;
protected volatile boolean mIsCountDownOn;
static final int MSG_RECOGNIZER_START_LISTENING = 1;
static final int MSG_RECOGNIZER_CANCEL = 2;
protected final String LOG_TAG = VoiceCommandService.class.getSimpleName();
@Override
public IBinder onBind(Intent intent) {
Log.d(LOG_TAG, "onBind");
return mServerMessenger.getBinder();
}
@Override
public void onCreate() {
super.onCreate();
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, false);
int maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_SYSTEM);
mAudioManager.setStreamVolume(AudioManager.STREAM_SYSTEM, maxVolume, AudioManager.FLAG_SHOW_UI);
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mSpeechRecognizer.setRecognitionListener(new SpeechRecognitionListener());
mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
this.getPackageName());
}
protected static class IncomingHandler extends Handler {
private WeakReference<VoiceCommandService> mtarget;
IncomingHandler(VoiceCommandService target) {
mtarget = new WeakReference<VoiceCommandService>(target);
}
@Override
public void handleMessage(Message msg) {
final VoiceCommandService target = mtarget.get();
switch (msg.what) {
case MSG_RECOGNIZER_START_LISTENING:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
// turn off beep sound
//target.mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, true);
}
if (!target.mIsListening){
target.mSpeechRecognizer.startListening(target.mSpeechRecognizerIntent);
target.mIsListening = true;
Log.d("IncomingHandler", "message start listening");
}
break;
case MSG_RECOGNIZER_CANCEL:
target.mSpeechRecognizer.cancel();
target.mIsListening = false;
Log.d("IncomingHandler", "message canceled recognizer");
break;
}
}
}
....
}