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);
Related
I'm making an app where I ask a question and the answering machine answers me depending on the question, but the problem is that the cell phone listens but it does not respond, that is, it does not talk.
She is speak in open app with welcome, but after no talk
My code
public class MainActivity extends AppCompatActivity {
private TextToSpeech myTTS;
private SpeechRecognizer mySpeechReconizer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Button mic = (Button) findViewById(R.id.mic);
mic.setOnClickListener((view) ->
{
Intent i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
i.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
mySpeechReconizer.startListening(i);
});
initializeTextToSpeech();
initializeSpeechReconizer();
}
private void initializeSpeechReconizer() {
if (SpeechRecognizer.isRecognitionAvailable(this)) {
mySpeechReconizer = SpeechRecognizer.createSpeechRecognizer(this);
mySpeechReconizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle params) {
}
#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) {
}
#Override
public void onResults(Bundle bundle) {
List<String> res = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
processResult(res.get(0));
}
#Override
public void onPartialResults(Bundle partialResults) {
}
#Override
public void onEvent(int eventType, Bundle params) {
}
});
}
}
private void processResult(String s) {
s = s.toLowerCase();
//Qual é o teu nome?
if (s.indexOf("What") != -1){
if (s.indexOf("your name") != -1){
speak("two");
}
if (s.indexOf("time") != -1){
Date now = new Date();
String time = DateUtils.formatDateTime(this,now.getTime(),
DateUtils.FORMAT_SHOW_TIME);
speak(time);
}
}
else if (s.indexOf("open") != -1){
if (s.indexOf("browser") != -1){
}
speak("Sou a Lian, fui fundada pelo Leandro e moro em Baião.");
}
}
private void initializeTextToSpeech() {
myTTS = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (myTTS.getEngines().size()==0){
Toast.makeText(MainActivity.this, "Teste", Toast.LENGTH_LONG).show();
finish();
} else {
Locale l1 = new Locale("pt","PT");
myTTS.setLanguage(l1);
speak("Olá Leandro, estou pronta,podes falar!");
}
}
});
}
private void speak(String s) {
if (Build.VERSION.SDK_INT >=21){
myTTS.speak(s,TextToSpeech.QUEUE_FLUSH,null,null);
} else{
myTTS.speak(s,TextToSpeech.QUEUE_FLUSH,null);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPause() {
super.onPause();
myTTS.shutdown();
}
}
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.
Here's my code:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_route);
SetupButton();
}
private void SetupButton()
{
Button createNewMessage = (Button) findViewById(R.id.button);
createNewMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ListenForNewMessage();
}
});
}
private void ListenForNewMessage()
{
final SpeechRecognizer newDeliverySpeech = SpeechRecognizer.createSpeechRecognizer(this);
RecognitionListener newDeliveryRecognitionListener = new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle params) {
Log.d("SpeechListening","onReadyForSpeech");
}
#Override
public void onBeginningOfSpeech() {
Log.d("SpeechListening","onBeginningOfSpeech");
}
#Override
public void onRmsChanged(float rmsdB) {
//do nothing
}
#Override
public void onBufferReceived(byte[] buffer) {
//do nothing
}
#Override
public void onEndOfSpeech() {
Log.d("SpeechListening","onEndOfSpeech");
}
#Override
public void onError(int error) {
//do nothing
}
#Override
public void onResults(Bundle results) {
ArrayList<String> userMessage;
userMessage = results.getStringArrayList(RESULTS_RECOGNITION);
PushNewDelivery(userMessage);
}
#Override
public void onPartialResults(Bundle partialResults) {
//do nothing
}
#Override
public void onEvent(int eventType, Bundle params) {
//do nothing
}
};
newDeliverySpeech.setRecognitionListener(newDeliveryRecognitionListener);
if (newDeliverySpeech.isRecognitionAvailable(getApplicationContext()))
{
Log.d("SpeechListening","started listening hopefully");
newDeliverySpeech.startListening(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH));
}
}
}
The problem is, only the started listening hopefully is logged, the RecognitionListener never has onReadyForSpeech() or any of its methods called.
Can someone please tell me what I'm doing wrong here?
You can change this below line
newDeliverySpeech.startListening(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH));
To,
Intent mSpeechIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechIntent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true);
mSpeechIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, "voice.recognition.test");
mSpeechIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
newDeliverySpeech.startListening(mSpeechIntent);
Ask the user for the permission to record audio before calling startListening:
String[] permissions = {Manifest.permission.RECORD_AUDIO};
ActivityCompat.requestPermissions(this, permissions, REQUEST_RECORD_AUDIO_PERMISSION);
https://developer.android.com/guide/topics/media/mediarecorder#audio-record-permission
Here's my code:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_route);
SetupButton();
}
private void SetupButton()
{
Button createNewMessage = (Button) findViewById(R.id.button);
createNewMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ListenForNewMessage();
}
});
}
private void ListenForNewMessage()
{
final SpeechRecognizer newDeliverySpeech = SpeechRecognizer.createSpeechRecognizer(this);
RecognitionListener newDeliveryRecognitionListener = new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle params) {
Log.d("SpeechListening","onReadyForSpeech");
}
#Override
public void onBeginningOfSpeech() {
Log.d("SpeechListening","onBeginningOfSpeech");
}
#Override
public void onRmsChanged(float rmsdB) {
//do nothing
}
#Override
public void onBufferReceived(byte[] buffer) {
//do nothing
}
#Override
public void onEndOfSpeech() {
Log.d("SpeechListening","onEndOfSpeech");
}
#Override
public void onError(int error) {
//do nothing
}
#Override
public void onResults(Bundle results) {
ArrayList<String> userMessage;
userMessage = results.getStringArrayList(RESULTS_RECOGNITION);
PushNewDelivery(userMessage);
}
#Override
public void onPartialResults(Bundle partialResults) {
//do nothing
}
#Override
public void onEvent(int eventType, Bundle params) {
//do nothing
}
};
newDeliverySpeech.setRecognitionListener(newDeliveryRecognitionListener);
if (newDeliverySpeech.isRecognitionAvailable(getApplicationContext()))
{
Log.d("SpeechListening","started listening hopefully");
newDeliverySpeech.startListening(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH));
}
}
}
The problem is, only the started listening hopefully is logged, the RecognitionListener never has onReadyForSpeech() or any of its methods called.
details
details
details
details
Can someone please tell me what I'm doing wrong here?
You are basically creating a new SpeechRecognizer object and register a new listener each time you click on the button. On top of that you create the SpeechRecognizer using the current Activity Context but you are actually using the Application context when calling: isRecognitionAvailable();
Try to create the SpeechRecognizer as a member object and register your listener when onCreate() is called. Also try to avoid using the Application context to avoid memory leaks.
Here is an example of how you should do it.
private SpeechRecognizer mDeliverySpeech;
private Intent mSpeechIntent;
private boolean mListening = false;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_route);
SetupButton();
SetupSpeechRecognizer();
mSpeechIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE, "en");
mSpeechIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, this.getPackageName());
mSpeechIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3);
}
private void SetupButton()
{
Button createNewMessage = (Button) findViewById(R.id.button);
createNewMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ListenForNewMessage();
}
});
}
private void SetupSpeechRecognizer()
{
mDeliverySpeech = SpeechRecognizer.createSpeechRecognizer(this);
RecognitionListener newDeliveryRecognitionListener = new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle params) {
Log.d("SpeechListening","onReadyForSpeech");
}
#Override
public void onBeginningOfSpeech() {
Log.d("SpeechListening","onBeginningOfSpeech");
}
#Override
public void onRmsChanged(float rmsdB) {
//do nothing
}
#Override
public void onBufferReceived(byte[] buffer) {
//do nothing
}
#Override
public void onEndOfSpeech() {
Log.d("SpeechListening","onEndOfSpeech");
}
#Override
public void onError(int error) {
//do nothing
}
#Override
public void onResults(Bundle results) {
ArrayList<String> userMessage;
userMessage = results.getStringArrayList(RESULTS_RECOGNITION);
PushNewDelivery(userMessage);
}
#Override
public void onPartialResults(Bundle partialResults) {
//do nothing
}
#Override
public void onEvent(int eventType, Bundle params) {
//do nothing
}
};
mDeliverySpeech.setRecognitionListener(newDeliveryRecognitionListener);
}
private void ListenForNewMessage()
{
if (mDeliverySpeech.isRecognitionAvailable(this) && !mListening)
{
Log.d("SpeechListening","started listening hopefully");
mListening = true;
mDeliverySpeech.startListening(mSpeechIntent);
new CountDownTimer(5000, 5000) {
public void onTick(long millisUntilFinished) {}
public void onFinish() {
mDeliverySpeech.stopListening();
mListening = false;
}
}.start();
}
}
Do not forget to properly handle the activity life cycle when working with listener to avoid memory leak.
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.