How do I use Android SpeechRecognizer as a service? - android

I am trying to run Android voice recognition as a service. I can verify that the onCreate() and onStart() methods of the service are called, but no callbacks to the speech recognition methods are called, despite the fact that I have set up the SpeechRecognizer object correctly. The speech recognition seems to work when it is done in an activity instead of a service. How do I make it work as a service? Is this a manifest issue?
package net.viralpatel.android.speechtotextdemo;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service implements RecognitionListener {
private SpeechRecognizer speechRecognizer;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d("tag", "onCreate");
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(getApplicationContext());
speechRecognizer.setRecognitionListener(this);
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
speechRecognizer.startListening(intent);
}
#Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d("tag", "onDestroy");
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d("tag", "onStart");
}
#Override
public void onBeginningOfSpeech() {
Log.d("Speech", "onBeginningOfSpeech");
}
#Override
public void onBufferReceived(byte[] buffer) {
Log.d("Speech", "onBufferReceived");
}
#Override
public void onEndOfSpeech() {
Log.d("Speech", "onEndOfSpeech");
}
#Override
public void onError(int error) {
Log.d("Speech", "onError");
}
#Override
public void onEvent(int eventType, Bundle params) {
Log.d("Speech", "onEvent");
}
#Override
public void onPartialResults(Bundle partialResults) {
Log.d("Speech", "onPartialResults");
}
#Override
public void onReadyForSpeech(Bundle params) {
Log.d("Speech", "onReadyForSpeech");
}
#Override
public void onResults(Bundle results) {
Log.d("Speech", "onResults");
ArrayList strlist = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
for (int i = 0; i < strlist.size();i++ ) {
Log.d("Speech", "result=" + strlist.get(i));
}
BufferedWriter out;
try {
out = new BufferedWriter(new FileWriter("mnt/sdcard/results.txt"));
// out.write(processor.execute(strlist.get(0).toString()));
out.write("hello world");
} catch (IOException e) {
Log.e("Speech",e.toString());
}
}
#Override
public void onRmsChanged(float rmsdB) {
Log.d("Speech", "onRmsChanged");
}
}

you can do this:
public class OpenMicService extends Service implements RecognitionListener{
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
private SpeechRecognizer speechRecognizer;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent,int flags,int startId) {
Toast.makeText(this,"start Service.",Toast.LENGTH_SHORT).show();
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(getApplicationContext());
speechRecognizer.setRecognitionListener(this);
Intent voice = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
voice.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass()
.getPackage().getName());
voice.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
voice.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 10);
speechRecognizer.startListening(voice);
return START_REDELIVER_INTENT;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#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) {
String wordStr = null;
String[] words = null;
String firstWord = null;
String secondWord = null;
ArrayList<String> matches = results
.getStringArrayList(speechRecognizer.RESULTS_RECOGNITION);
wordStr = matches.get(0);
words = wordStr.split(" ");
firstWord = words[0];
secondWord = words[1];
if (firstWord.equals("open")) {
PackageManager packageManager = getPackageManager();
List<PackageInfo> packs = packageManager
.getInstalledPackages(0);
int size = packs.size();
boolean uninstallApp = false;
boolean exceptFlg = false;
for (int v = 0; v < size; v++) {
PackageInfo p = packs.get(v);
String tmpAppName = p.applicationInfo.loadLabel(
packageManager).toString();
String pname = p.packageName;
//URL urlAddress = urlAddress.toLowerCase();
tmpAppName = tmpAppName.toLowerCase();
if (tmpAppName.trim().toLowerCase().equals(secondWord.trim().toLowerCase())) {
PackageManager pm = this.getPackageManager();
Intent appStartIntent = pm.getLaunchIntentForPackage(pname);
if (null != appStartIntent) {
try {
this.startActivity(appStartIntent);
} catch (Exception e) {
}
}
}
}
} // end of open app code
}
#Override
public void onPartialResults(Bundle bundle) {
}
#Override
public void onEvent(int i,Bundle bundle) {
}
}

There are 2 things that I think you need to clarify and may provide you as a workaround.
Have declared the service in the manifest properly?
I believe this is something already addressed.
Speech recognition may not start "onCreate" of the service. I had done similar implementation but it didn't work. You can try placing the startListening(intent) in some other method and call it explicitly. This worked for me.
Let me know if it helps.

Related

How to pause/play background music in MainActivity in Android?

I'm calling the service MusicaFundo in Splashscreen.class and want to pause/play it in MainActivity.class.
I'm trying with a sendBroadcast but the service is not receiving the intent, I have created the BroadcastReceiver, MyServiceReceiver, inside MusicaFundo.class, is it wrong to do like this?
MainActivity.class
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
boolean musicaTocar = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent svc = new Intent (this, MusicaFundo.class);
TextView titulo = findViewById(R.id.titulo);
final ImageView som = findViewById(R.id.som);
som.setBackgroundResource(R.drawable.volumeup);
final ImageView jogomem = findViewById(R.id.jogomem);
jogomem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Animation diminuir = (Animation) AnimationUtils.loadAnimation(MainActivity.this, R.anim.diminuir);
jogomem.startAnimation(diminuir);
Intent jogomemoria = new Intent(MainActivity.this, JogoMemoria.class);
startActivity(jogomemoria);
}
});
Animation deslocarD = (Animation) AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left);
titulo.startAnimation(deslocarD);
som.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!musicaTocar){
som.setBackgroundResource(R.drawable.volumemut);
playMusica();
musicaTocar = true;
}
else {
if (musicaTocar){
som.setBackgroundResource(R.drawable.volumeup);
pausarMusica();
musicaTocar = false;
}
}
}
});
}
private void pausarMusica() {
Intent pausar = new Intent();
pausar.setAction("pausar");
sendBroadcast(pausar);
}
private void playMusica() {
Intent tocar = new Intent();
tocar.setAction("tocarmusica");
sendBroadcast(tocar);
}
Inside MusicaFundo.class
public class MusicaFundo extends Service {
private MediaPlayer player;
public int posatual = 0;
private static final String TAG = "MusicaFundo";
public static Object getName() {
return null;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate(){
player = MediaPlayer.create(this, R.raw.musicafundo);
player.setLooping(true);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
player.seekTo(posatual);
player.start();
return START_STICKY;
}
public boolean onUnbind(Intent intent){
return false;
}
#Override
public void onDestroy() {
super.onDestroy();
if (player != null) {
if (player.isPlaying()) {
player.stop();
}
player.release();
}
}
public void resumeMusic(){
if (player != null) {
if (player.isPlaying() == false) {
player.seekTo(posatual);
player.start();
}
}
}
public void onPause(){
if (player != null) {
if (player.isPlaying()) {
posatual = player.getCurrentPosition();
player.pause();
}
}
}
public class MyServiceReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String pausa = intent.getAction();
if(pausa.equals("pausar")){
onPause();
Log.d(TAG, "onReceive: " + pausa);
}
else if(pausa.equals("tocarmusica")){
resumeMusic();
Log.d(TAG, "onReceive: " + pausa);
}
}
}
Want to receive intent so it compares the string to pause or play.
Not sure if the code is just not complete in the question but you need to call registerReceiver in your service for the receiver to actually receive broadcasts.
Also, if this is mostly communication within the same process, I suggest using LocarBroadcastManager as it is more efficient and secure.

Android: SpeechRecognizer Listening Timeout

How to use SpeechRecognizer continuously without timeout. This is my code i am getting result on textview but this stops after listening few seconds. In my case i have to start until user don't stop it or it should stop after 15 to 20 minutes. if this is possible then please suggest me how to do. i want to increase timeout delay.
public class VoiceService extends Service {
String result;
private SpeechRecognizer sr;
class listener implements RecognitionListener {
listener() {
}
public void onReadyForSpeech(Bundle params) {
}
public void onBeginningOfSpeech() {Toast.makeText(VoiceService.this, "Listening", Toast.LENGTH_SHORT).show();}
public void onRmsChanged(float rmsdB) {
}
public void onBufferReceived(byte[] buffer) {
}
public void onEndOfSpeech() {
Toast.makeText(VoiceService.this, "Stopped", Toast.LENGTH_SHORT).show();
}
public void onError(int error) {
}
public void onResults(Bundle results) {
ArrayList<String> matches =
results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if (matches != null){
FragmentTwo.textViewresult.setText(matches.get(0));}
}
public void onPartialResults(Bundle partialResults) {
}
public void onEvent(int eventType, Bundle params) {
}
}
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service Started",
Toast.LENGTH_SHORT).show();
AudioManager amanager = (AudioManager)
getSystemService("audio");
amanager.setStreamMute(3, true);
amanager.setStreamMute(1, true);
onClickk();
}
public void onDestroy() {
super.onDestroy();
if (this.sr != null) {
this.sr.destroy();
}
Toast.makeText(this, "Voice Service Stopped", Toast.LENGTH_SHORT).show();
}
public void onClickk() {
if (this.sr != null) {
this.sr.destroy();
}
this.sr = SpeechRecognizer.createSpeechRecognizer(this);
this.sr.setRecognitionListener(new listener());
Intent intent = new Intent("android.speech.action.RECOGNIZE_SPEECH");
intent.putExtra("android.speech.extra.LANGUAGE_MODEL", "free_form");
intent.putExtra("android.speech.extra.MAX_RESULTS", 1);
this.sr.startListening(intent);
}}

Trying to implement a speech to text, don't know what is wrong

New to Android development, trying to implement a speech to text that will print the words on the screen in real time but getting the below error. Can't seem to understand where the problem is. Is it because I am calling the startRecording() and stopRecording() from the togglebutton events or is is it something else entirely.
com.example.android.moviebud E/SpeechRecognizer: not connected to the recognition service
package com.example.android.moviebud;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.support.v7.app.AppCompatActivity;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends AppCompatActivity implements RecognitionListener {
ToggleButton recBtn;
SpeechRecognizer recognizer;
Intent recognitionIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
recognizer = SpeechRecognizer.createSpeechRecognizer(this);
recognizer.setRecognitionListener(this);
recognitionIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recBtn = (ToggleButton) findViewById(R.id.recBtn);
recBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked) {
recognizer.startListening(recognitionIntent);
} else {
recognizer.stopListening();
recognizer.destroy();
}
}
});
}
#Override
public void onReadyForSpeech(Bundle bundle) {
Toast.makeText(getApplicationContext(), "READY", Toast.LENGTH_SHORT).show();
}
#Override
public void onBeginningOfSpeech() {
Toast.makeText(getApplicationContext(), "Speech recognition started", Toast.LENGTH_SHORT).show();
}
#Override
public void onRmsChanged(float v) {
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int i) {
Toast.makeText(getApplicationContext(), "Some error occurred", Toast.LENGTH_SHORT).show();
}
#Override
public void onResults(Bundle bundle) {
TextView v = (TextView) findViewById(R.id.speech);
StringBuilder sb = new StringBuilder("");
for (String s : bundle.getStringArrayList(recognizer.RESULTS_RECOGNITION)) {
sb.append(s);
}
v.setText(sb.toString());
}
#Override
public void onPartialResults(Bundle bundle) {
}
#Override**strong text**
public void onEvent(int i, Bundle bundle) {
}
}
Try this code it is working, I have done it.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkPermission();
final EditText editText = findViewById(R.id.editText);
final SpeechRecognizer mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
final Intent mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,
Locale.getDefault());
mSpeechRecognizer.setRecognitionListener(new RecognitionListener() {
#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 bundle) {
//getting all the matches
ArrayList<String> matches = bundle
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
//displaying the first match
if (matches != null)
editText.setText(matches.get(0));
}
#Override
public void onPartialResults(Bundle bundle) {
}
#Override
public void onEvent(int i, Bundle bundle) {
}
});
findViewById(R.id.button).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_UP:
mSpeechRecognizer.stopListening();
editText.setHint("You will see input here");
break;
case MotionEvent.ACTION_DOWN:
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
editText.setText("");
editText.setHint("Listening...");
break;
}
return false;
}
});
}
private void checkPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!(ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED)) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.parse("package:" + getPackageName()));
startActivity(intent);
finish();
}
}
}
}
Fore more details you can visit my blog post - Android Speech To Text Tutorial.

onReadyForSpeech calling multiple times while continuous Speech Recognition

I am creating an application in that i need continuous speech recognition. But onReadyForSpeech calling two times.
I am also attaching my code. Please help me to find out the problem.
Thanks in advance.
private SpeechRecognizer mSpeechRecognizer = null;
public static VoiceRecognizeService sVoiceRecognizeService;
private ITelephony mListener;
private boolean isListening;
private Intent mSaverController;
public VoiceRecognizeService() {
super();
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
sVoiceRecognizeService = this;
startListening();
return START_NOT_STICKY;
}
public void setTelephonyListener(ITelephony mListener) {
this.mListener = mListener;
}
public static VoiceRecognizeService getInstance() {
return sVoiceRecognizeService;
}
// starts the service
public void startListening() {
if (!isListening) {
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mSpeechRecognizer.setRecognitionListener(this);
Intent mRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en_IN");
mRecognizerIntent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS, 2000);
mRecognizerIntent.putExtra("android.speech.extra.DICTATION_MODE", true);
mRecognizerIntent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, false);
mRecognizerIntent.putExtra("android.speech.extra.PREFER_OFFLINE", true);
mRecognizerIntent.putExtra("calling_package", this.getPackageName());
mSpeechRecognizer.startListening(mRecognizerIntent);
isListening = true;
}
}
public void processVoiceCommands(final ArrayList<String> partialData) {
}
public void restartListeningService() {
cancelSpeechRecognition();
startListening();
}
public void cancelSpeechRecognition() {
if (mSpeechRecognizer != null) {
mSpeechRecognizer.stopListening();
mSpeechRecognizer.cancel();
mSpeechRecognizer.destroy();
mSpeechRecognizer = null;
isListening = false;
}
}
#Override
public void onReadyForSpeech(Bundle bundle) {
Log.e("VoiceError", "speechReady");
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float scale) {
if (mListener != null) {
mListener.onRmsChanged(scale);
}
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int i) {
if (i == SpeechRecognizer.ERROR_RECOGNIZER_BUSY) {
} else {
restartListeningService();
}
}
#Override
public void onResults(Bundle bundle) {
final ArrayList<String> data = bundle.getStringArrayList(
SpeechRecognizer.RESULTS_RECOGNITION);
if (data != null) {
processVoiceCommands(data);
}
restartListeningService();
}
#Override
public void onPartialResults(Bundle bundle) {
final ArrayList<String> data = bundle.getStringArrayList(
SpeechRecognizer.RESULTS_RECOGNITION);
Log.e("VoiceError", "partialResults " + data);
}
#Override
public void onEvent(int i, Bundle bundle) {
}
#Override
public void onDestroy() {
if (mSpeechRecognizer != null) {
mSpeechRecognizer.setRecognitionListener(null);
cancelSpeechRecognition();
}
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}

Jelly Bean Beep In Speech Recognition

I've been looking through different threads and haven't found anything that has worked for me on the problem that I am experiencing. I'd like to get rid of the "beep" sound that you get when speech recognition starts. I'm working with Jelly Bean 4.2.2 so I'm not sure if the same problem is on early versions, if it is I'd also like a fix for that. Also, I was wondering if anyone has suggestions on how to respond to certain Speech Recognition Results. Please let me know how my code can be improvised to include those features.
package com.example.speech;
import java.util.ArrayList;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.app.Activity;
import android.content.Intent;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.view.Menu;
import android.view.View.OnClickListener;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.util.Log;
public class MainActivity extends Activity implements OnClickListener {
ListView lv;
private SpeechRecognizer mSpeechRecognizer;
private Intent mSpeechRecognizerIntent;
boolean reseter = false;
private AudioManager mAudioManager;
private volatile boolean mNoSpeechCountDownOn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
boolean available = SpeechRecognizer.isRecognitionAvailable(this);
Log.d("Speech", "available = " + available);
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mSpeechRecognizer.setRecognitionListener(new SpeechListener());
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());
mAudioManager = (AudioManager) getSystemService(this.AUDIO_SERVICE);
commandA();
}
private CountDownTimer mNoSpeechCountDown = new CountDownTimer(5000, 5000)
{
#Override
public void onTick(long millisUntilFinished)
{
}
#SuppressWarnings("synthetic-access")
#Override
public void onFinish()
{
mNoSpeechCountDownOn = false;
mSpeechRecognizer.cancel();
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class SpeechListener implements RecognitionListener {
#Override
public void onBeginningOfSpeech() {
if (mNoSpeechCountDownOn)
{
mNoSpeechCountDownOn = false;
mNoSpeechCountDown.cancel();
}
Log.d("Speech", "onBeginningOfSpeech");
}
#Override
public void onBufferReceived(byte[] buffer) {
Log.d("Speech", "onBufferReceived");
}
#Override
public void onEndOfSpeech() {
Log.d("Speech", "onEndOfSpeech");
}
#Override
public void onError(int error) {
if (mNoSpeechCountDownOn)
{
mNoSpeechCountDownOn = false;
mNoSpeechCountDown.cancel();
}
Log.d("Speech", "onError");
}
#Override
public void onEvent(int eventType, Bundle params) {
Log.d("Speech", "onEvent");
}
#Override
public void onPartialResults(Bundle partialResults) {
Log.d("Speech", "onPartialResults");
}
#Override
public void onReadyForSpeech(Bundle params) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
{
mNoSpeechCountDownOn = true;
mNoSpeechCountDown.start();
mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, false);
}
Log.d("Speech", "onReadyForSpeech");
try {
Thread.sleep(4900);
} catch (InterruptedException e) {
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, true);
Log.d("speech", "Mute on");
}
}
#Override
public void onResults(Bundle results) {
Log.d("Speech", "results");
ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
// Do whatever you want here
try {
Thread.sleep(1);
} catch (InterruptedException e) {
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, true);
Log.d("speech", "Mute on");
}
}
#Override
public void onRmsChanged(float rmsdB) {
//Log.d("Speech", "onRmsChanged");
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
public class MainActivity extends Activity implements OnClickListener {
ListView lv;
private SpeechRecognizer mSpeechRecognizer;
private Intent mSpeechRecognizerIntent;
boolean reseter = false;
private AudioManager mAudioManager;
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView)findViewById(R.id.lvVoiceReturn);
Button b= (Button)findViewById(R.id.bVoice);
b.setOnClickListener(this);
boolean available = SpeechRecognizer.isRecognitionAvailable(this);
Log.d("Speech", "available = " + available);
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mSpeechRecognizer.setRecognitionListener(new SpeechListener());
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());
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
}
private CountDownTimer mNoSpeechCountDown = new CountDownTimer(5000, 5000)
{
#Override
public void onTick(long millisUntilFinished)
{
}
#SuppressWarnings("synthetic-access")
#Override
public void onFinish()
{
mNoSpeechCountDownOn = false;
mSpeechRecognizer.cancel();
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub`
Log.d("speech", "button active");
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, true);
}
private class SpeechListener implements RecognitionListener {
#Override
public void onBeginningOfSpeech() {
if (mNoSpeechCountDownOn)
{
mNoSpeechCountDownOn = false;
mNoSpeechCountDown.cancel();
}
Log.d("Speech", "onBeginningOfSpeech");
}
#Override
public void onBufferReceived(byte[] buffer) {
Log.d("Speech", "onBufferReceived");
}
#Override
public void onEndOfSpeech() {
Log.d("Speech", "onEndOfSpeech");
}
#Override
public void onError(int error) {
if (mNoSpeechCountDownOn)
{
mNoSpeechCountDownOn = false;
mNoSpeechCountDown.cancel();
}
Log.d("Speech", "onError");
}
#Override
public void onEvent(int eventType, Bundle params) {
Log.d("Speech", "onEvent");
}
#Override
public void onPartialResults(Bundle partialResults) {
Log.d("Speech", "onPartialResults");
}
#Override
public void onReadyForSpeech(Bundle params) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
{
mNoSpeechCountDownOn = true;
mNoSpeechCountDown.start();
mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, false);
}
Log.d("Speech", "onReadyForSpeech");
}
#Override
public void onResults(Bundle results) {
Log.d("Speech", "results");
ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
// Do whatever you want here
}
#Override
public void onRmsChanged(float rmsdB) {
//Log.d("Speech", "onRmsChanged");
}
}
}
#Hoan Nguyen : The only way I found to mute the "beep" when SpeechRecognizer starts listening was to use the following :
mAudioManager.setStreamSolo(AudioManager.STREAM_VOICE_CALL, true);
It is a nasty hack, as I simply want to mute the kind of 'system sound' played by the SpeechRecognizer, but the other solution, using mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, true) was not effective.
Try to use this code:
mAudioManager.setStreamMute(AudioManager.VIBRATE_TYPE_NOTIFICATION, true);

Categories

Resources