Hi,
I have created a sample app for voice recognition using PocketSphinx. But while launching app , it got crashed. No exceptions and error showing in the logcat. And as per the troubleshooting , i found like crash happening with getRecognizer() method call. But I am unable to fix or find the error. I'm using android versions 8 to latest(13).Please see my complete code below
public class MainActivity extends AppCompatActivity implements
RecognitionListener
{
private static final String KWS_SEARCH = "wakeup";
private static final String FORECAST_SEARCH = "forecast";
private static final String DIGITS_SEARCH = "digits";
private static final String PHONE_SEARCH = "phones";
private static final String MENU_SEARCH = "menu";
/*Keywordwearelookingfortoactivatemenu*/privatestaticfinalStringKEYPHRASE="oh mighty computer";/*Usedtohandlepermissionrequest*/privatestaticfinalintPERMISSIONS_REQUEST_RECORD_AUDIO=1;privatestaticfinalintMY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE=2;privateSpeechRecognizerrecognizer;privateHashMap<String,Integer>captions;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);if(BuildConfig.DEBUG){StrictMode.setThreadPolicy(newStrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build());StrictMode.setVmPolicy(newStrictMode.VmPolicy.Builder().detectAll().penaltyLog().build());}captions=newHashMap<>();captions.put(KWS_SEARCH,R.string.kws_caption);captions.put(MENU_SEARCH,R.string.menu_caption);captions.put(DIGITS_SEARCH,R.string.digits_caption);captions.put(PHONE_SEARCH,R.string.phone_caption);captions.put(FORECAST_SEARCH,R.string.forecast_caption);((TextView)findViewById(R.id.caption_text)).setText("Preparing the recognizer");if(ContextCompat.checkSelfPermission(getApplicationContext(),Manifest.permission.READ_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED){//RequestpermissiontoreadfilesActivityCompat.requestPermissions(this,newString[]{Manifest.permission.READ_EXTERNAL_STORAGE},MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);return;}//CheckifuserhasgivenpermissiontorecordaudiointpermissionCheck=ContextCompat.checkSelfPermission(getApplicationContext(),Manifest.permission.RECORD_AUDIO);if(permissionCheck!=PackageManager.PERMISSION_GRANTED){ActivityCompat.requestPermissions(this,newString[]{android.Manifest.permission.RECORD_AUDIO},PERMISSIONS_REQUEST_RECORD_AUDIO);return;}//Recognizerinitializationisatime-consuminganditinvolvesIO,//soweexecuteitinasynctasknewSetupTask(this).execute();}privatestaticclassSetupTaskextendsAsyncTask<Void,Void,Exception>{WeakReference<MainActivity>activityReference;SetupTask(MainActivityactivity){this.activityReference=newWeakReference<>(activity);}@OverrideprotectedExceptiondoInBackground(Void...params){try{Assetsassets=newAssets(activityReference.get());FileassetDir=assets.syncAssets();activityReference.get().setupRecognizer(assetDir);}catch(IOExceptione){Log.d("print IO Ecception ",e.getMessage());returne;}returnnull;}@OverrideprotectedvoidonPostExecute(Exceptionresult){if(result!=null){((TextView)activityReference.get().findViewById(R.id.caption_text)).setText("Failed to init recognizer "+result);}else{activityReference.get().switchSearch(KWS_SEARCH);}}}@OverridepublicvoidonRequestPermissionsResult(intrequestCode,@NonNullString[]permissions,@NonNullint[]grantResults){super.onRequestPermissionsResult(requestCode,permissions,grantResults);if(requestCode==PERMISSIONS_REQUEST_RECORD_AUDIO){if(grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){//Recognizerinitializationisatime-consuminganditinvolvesIO,//soweexecuteitinasynctasknewSetupTask(this).execute();}else{finish();}}}@OverridepublicvoidonDestroy(){super.onDestroy();if(recognizer!=null){recognizer.cancel();recognizer.shutdown();}}/***Inpartialresultwegetquickupdatesaboutcurrenthypothesis.In*keywordspottingmodewecanreacthere,inothermodesweneedtowait*forfinalresultinonResult.*/@OverridepublicvoidonPartialResult(Hypothesishypothesis){if(hypothesis==null)return;Stringtext=hypothesis.getHypstr();if(text.equals(KEYPHRASE))switchSearch(MENU_SEARCH);elseif(text.equals(DIGITS_SEARCH))switchSearch(DIGITS_SEARCH);elseif(text.equals(PHONE_SEARCH))switchSearch(PHONE_SEARCH);elseif(text.equals(FORECAST_SEARCH))switchSearch(FORECAST_SEARCH);else((TextView)findViewById(R.id.result_text)).setText(text);}/***Thiscallbackiscalledwhenwestoptherecognizer.*/@OverridepublicvoidonResult(Hypothesishypothesis){((TextView)findViewById(R.id.result_text)).setText("");if(hypothesis!=null){Stringtext=hypothesis.getHypstr();Toast.makeText(getApplicationContext(),text,Toast.LENGTH_SHORT).show();}}@OverridepublicvoidonBeginningOfSpeech(){}/***Westoprecognizerheretogetafinalresult*/@OverridepublicvoidonEndOfSpeech(){if(!recognizer.getSearchName().equals(KWS_SEARCH))switchSearch(KWS_SEARCH);}privatevoidswitchSearch(StringsearchName){recognizer.stop();//Ifwearenotspotting,startlisteningwithtimeout(10000msor10seconds).if(searchName.equals(KWS_SEARCH))recognizer.startListening(searchName);elserecognizer.startListening(searchName,10000);Stringcaption=getResources().getString(captions.get(searchName));((TextView)findViewById(R.id.caption_text)).setText(caption);}privatevoidsetupRecognizer(FileassetsDir)throwsIOException{//Therecognizercanbeconfiguredtoperformmultiplesearches//ofdifferentkindandswitchbetweenthemFileacousticModel=newFile(assetsDir,"en-us-ptm");Filedictionary=newFile(assetsDir,"cmudict-en-us.dict");if(acousticModel.exists()){Log.d("SetupRecognizer","Acoustic Model Path: "+acousticModel.getAbsolutePath());}if(dictionary.exists()){Log.d("SetupRecognizer","Dictionary Path: "+dictionary.getAbsolutePath());}try{recognizer=SpeechRecognizerSetup.defaultSetup().setAcousticModel(acousticModel).setDictionary(dictionary).getRecognizer();if(recognizer!=null){Log.d("SetupRecognizer","After initializing recognizer");recognizer.addListener(this);Log.d("SetupRecognizer","Listener attached successfully");}else{Log.e("SetupRecognizer","Recognizer is null after initialization");}}catch(IOExceptione){Log.e("SetupRecognizer","Error setting up recognizer",e);return;}}@OverridepublicvoidonTimeout(){switchSearch(KWS_SEARCH);}@OverridepublicvoidonError(Exceptione){((TextView)findViewById(R.id.caption_text)).setText(e.getMessage());}
Hi,
I have created a sample app for voice recognition using PocketSphinx. But while launching app , it got crashed. No exceptions and error showing in the logcat. And as per the troubleshooting , i found like crash happening with getRecognizer() method call. But I am unable to fix or find the error. I'm using android versions 8 to latest(13).Please see my complete code below
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Locale;
import edu.cmu.pocketsphinx.Assets;
import edu.cmu.pocketsphinx.BuildConfig;
import edu.cmu.pocketsphinx.Hypothesis;
import edu.cmu.pocketsphinx.RecognitionListener;
import edu.cmu.pocketsphinx.SpeechRecognizer;
import edu.cmu.pocketsphinx.SpeechRecognizerSetup;
public class MainActivity extends AppCompatActivity implements
RecognitionListener
{
private static final String KWS_SEARCH = "wakeup";
private static final String FORECAST_SEARCH = "forecast";
private static final String DIGITS_SEARCH = "digits";
private static final String PHONE_SEARCH = "phones";
private static final String MENU_SEARCH = "menu";
}