Advertisement
alfacentaury

MainActivity.java

Apr 25th, 2017
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 14.53 KB | None | 0 0
  1. package com.example.asus.biometriksuara;
  2.  
  3. import android.app.Activity;
  4. import android.app.Dialog;
  5. import android.app.ProgressDialog;
  6. import android.content.ComponentName;
  7. import android.content.Context;
  8. import android.content.Intent;
  9. import android.content.SharedPreferences;
  10. import android.content.pm.ActivityInfo;
  11. import android.content.pm.ResolveInfo;
  12. import android.os.AsyncTask;
  13. import android.os.Bundle;
  14. import android.util.Log;
  15. import android.view.Menu;
  16. import android.view.MenuItem;
  17. import android.view.View;
  18. import android.widget.AdapterView;
  19. import android.widget.Button;
  20. import android.widget.EditText;
  21. import android.widget.ListView;
  22. import android.widget.Toast;
  23.  
  24. import java.io.File;
  25. import java.io.IOException;
  26. import java.net.MalformedURLException;
  27. import java.net.URL;
  28. import java.util.HashMap;
  29. import java.util.HashSet;
  30. import java.util.LinkedList;
  31. import java.util.List;
  32. import java.util.Map;
  33. import java.util.Set;
  34. import java.util.concurrent.ExecutionException;
  35.  
  36. import SphinxDemo.sphinx4.edu.cmu.sphinx.frontend.Data;
  37. import SphinxDemo.sphinx4.edu.cmu.sphinx.frontend.DataEndSignal;
  38. import SphinxDemo.sphinx4.edu.cmu.sphinx.frontend.DataProcessor;
  39. import SphinxDemo.sphinx4.edu.cmu.sphinx.frontend.FloatData;
  40. import SphinxDemo.sphinx4.edu.cmu.sphinx.frontend.FrontEnd;
  41. import SphinxDemo.sphinx4.edu.cmu.sphinx.frontend.endpoint.SpeechEndSignal;
  42. import SphinxDemo.sphinx4.edu.cmu.sphinx.frontend.endpoint.SpeechStartSignal;
  43. import SphinxDemo.sphinx4.edu.cmu.sphinx.frontend.util.AudioFileDataSource;
  44. import SphinxDemo.sphinx4.edu.cmu.sphinx.util.props.ConfigurationManager;
  45.  
  46.  
  47. public class SpeechActivity extends Activity {
  48.  
  49.     //Activity View Objects
  50.     Button btn_test;
  51.     Button btn_add;
  52.     ListView list;
  53.     ApplicationListAdapter adapter;
  54.     ResolveInfo info;
  55.     String ID = "";
  56.     EditText txt_id;
  57.  
  58.     //SPHINX specific variables
  59.     DataProcessor last_d;
  60.     Context con;
  61.     AudioFileDataSource dataSource;
  62.     URL audioURL;
  63.     ConfigurationManager cm;
  64.     FrontEnd frontend;
  65.     URL configURL;
  66.     boolean speechStarted = false;
  67.     boolean speechEnded = false;
  68.     boolean isRecognizerInit = false;
  69.  
  70.     //Action Map
  71.     Map<String, ResolveInfo> action_map;
  72.  
  73.     @Override
  74.     protected void onCreate(Bundle savedInstanceState) {
  75.         super.onCreate(savedInstanceState);
  76.         setContentView(R.layout.activity_speech);
  77.         startActivity(new Intent(getBaseContext(), NumberActivity.class));
  78.         con = this;
  79.         action_map = new HashMap<String, ResolveInfo>();
  80.         initActivityParams();
  81.         try {
  82.             init_sphinx_params();
  83.         } catch (IOException e) {
  84.             Toast.makeText(this, "Unable to Initialize Sphinx parameters, try reinstalling the application", Toast.LENGTH_LONG).show();
  85.             isRecognizerInit = false;
  86.             Log.d("SPHINX_LOG", "PARAM_INIT_FAILURE");
  87.             e.printStackTrace();
  88.         }
  89.  
  90.     }
  91.  
  92.     @Override
  93.     protected void onResume() {
  94.         super.onResume();
  95.  
  96.     }
  97.  
  98.     @Override
  99.     protected void onPause() {
  100.         super.onPause();
  101.         switch (Config.voice_method) {
  102.             case Constant.METHOD_ADD: {
  103.                 ID = txt_id.getText().toString();
  104.                 if (ID.length() < 1) {
  105.                     Toast.makeText(getBaseContext(), "ID is not entered", Toast.LENGTH_SHORT).show();
  106.                     Config.voice_method = -1;
  107.                 }
  108.  
  109.             }
  110.         }
  111.     }
  112.  
  113.     @Override
  114.     protected void onStop() {
  115.         super.onStop();
  116.         Config.voice_method = -1;
  117.  
  118.     }
  119.  
  120.     private void initActivityParams() {
  121.         final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
  122.         mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
  123.         list = (ListView) findViewById(R.id.app_list);
  124.         List pkgAppsList = con.getPackageManager().queryIntentActivities(mainIntent, 0);
  125.         if (pkgAppsList == null || pkgAppsList.size() < 1) {
  126.             Toast.makeText(getBaseContext(), "No applications found or error in loading application list", Toast.LENGTH_SHORT).show();
  127.  
  128.         } else {
  129.             adapter = new ApplicationListAdapter(pkgAppsList, con);
  130.             info = adapter.getItem(0);
  131.             list.setAdapter(adapter);
  132.             list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  133.  
  134.                 @Override
  135.                 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  136.                     //startApp(adapter.getItem(position));
  137.                     Log.d("ITEM_CLICK", "Item " + position + " clicked");
  138.                     info = adapter.getItem(position);
  139.                 }
  140.             });
  141.         }
  142.         btn_add = (Button) findViewById(R.id.btn_add_sample);
  143.         btn_test = (Button) findViewById(R.id.test_button);
  144.         txt_id = (EditText) findViewById(R.id.txt_id);
  145.         btn_add.setOnClickListener(new View.OnClickListener() {
  146.             @Override
  147.             public void onClick(View v) {
  148.                 Config.voice_method = Constant.METHOD_ADD;
  149.                 if (txt_id.getText().toString().length() < 1) {
  150.                     Toast.makeText(getBaseContext(), "Please do give a unique ID for the application", Toast.LENGTH_SHORT).show();
  151.                     Config.voice_method = -1;
  152.                 } else {
  153.                     startActivityForResult(new Intent(con, RecordAudioSample.class), Constant.METHOD_ADD);
  154.                     //startActivity(new Intent(con, RecordAudioSample.class));
  155.                 }
  156.  
  157.             }
  158.         });
  159.         btn_test.setOnClickListener(new View.OnClickListener() {
  160.             @Override
  161.             public void onClick(View v) {
  162.                 Config.voice_method = Constant.METHOD_TEST;
  163.                 startActivityForResult(new Intent(con, RecordAudioSample.class), Constant.METHOD_TEST);
  164.  
  165.             }
  166.         });
  167.     }
  168.  
  169.     public void startApp(ResolveInfo item) {
  170.         ActivityInfo activity = item.activityInfo;
  171.         ComponentName name = new ComponentName(activity.applicationInfo.packageName,
  172.                 activity.name);
  173.         Intent i = new Intent(Intent.ACTION_MAIN);
  174.  
  175.         i.addCategory(Intent.CATEGORY_LAUNCHER);
  176.         i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
  177.                 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
  178.         i.setComponent(name);
  179.  
  180.         startActivity(i);
  181.     }
  182.  
  183.  
  184.     @Override
  185.     public boolean onCreateOptionsMenu(Menu menu) {
  186.         // Inflate the menu; this adds items to the action bar if it is present.
  187.         getMenuInflater().inflate(R.menu.menu_speech, menu);
  188.         return true;
  189.     }
  190.  
  191.     /**
  192.      * Perform Voice recognition and collects the vectors into the ResultCollector class.
  193.      */
  194.     void doRecognition() {
  195.         try {
  196.             init_sphinx_params();
  197.         } catch (IOException e) {
  198.             Log.d("IOEXC", "In doRecognition");
  199.             e.printStackTrace();
  200.         }
  201.         ResultCollector.resetData();
  202.         Data d;
  203.         frontend.initialize();
  204.         last_d = frontend.getLastDataProcessor();
  205.         int s = 0;
  206.         while (!((d = last_d.getData()) instanceof DataEndSignal)) {
  207.  
  208.             if (d instanceof FloatData) {
  209.                 if (speechStarted && !speechEnded) {
  210.                     ResultCollector.CollectResult((FloatData) d);
  211.                     s++;
  212.                 }
  213.             } else if (d instanceof SpeechStartSignal) {
  214.                 Log.d("SPEECH_LOG", "Start of a speech!\n");
  215.                 speechStarted = true;
  216.  
  217.             } else if (d instanceof SpeechEndSignal) {
  218.                 Log.d("SPEECH_LOG", "End of a speech\n");
  219.                 speechEnded = true;
  220.             }
  221.         }
  222.         Log.d("SPEECH_SIZE", "" + s);
  223.         speechStarted = false;
  224.         speechEnded = false;
  225.  
  226.     }
  227.  
  228.  
  229.     @Override
  230.     public boolean onOptionsItemSelected(MenuItem item) {
  231.         // Handle action bar item clicks here. The action bar will
  232.         // automatically handle clicks on the Home/Up button, so long
  233.         // as you specify a parent activity in AndroidManifest.xml.
  234.         int id = item.getItemId();
  235.  
  236.         //noinspection SimplifiableIfStatement
  237.         if (id == R.id.action_settings) {
  238.             return true;
  239.         } else
  240.             return super.onOptionsItemSelected(item);
  241.     }
  242.  
  243.     @Override
  244.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  245.         switch (requestCode) {
  246.             case Constant.METHOD_ADD: {
  247.                 SharedPreferences samples = getSharedPreferences(Constant.PREF_SAMPLES, MODE_PRIVATE);
  248.                 SharedPreferences.Editor samples_editor = samples.edit();
  249.                 String s = "";
  250.                 s = data.getStringExtra(Constant.PREF_KEY_TMP_FILE);
  251.                 try {
  252.                     audioURL = new File(s).toURI().toURL();
  253.                 } catch (MalformedURLException e) {
  254.                     e.printStackTrace();
  255.                     Toast.makeText(con, "Malformed URL", Toast.LENGTH_SHORT).show();
  256.                     return;
  257.                 }
  258.                 doRecognition();
  259.                 try {
  260.                     VoiceAnalyzer.samples.put(ID, ResultCollector.list);
  261.                     Log.d("ANALYSIS_RESULT", ID);
  262.                     Set<String> list = samples.getStringSet(Constant.PRES_SAMPLES_KEY, new HashSet<String>());
  263.                     list.add(ID);
  264.                     samples_editor.putStringSet(Constant.PRES_SAMPLES_KEY, list);
  265.                     action_map.put(ID, info);
  266.                     Toast.makeText(getBaseContext(), "Added trigger to hashmap!", Toast.LENGTH_SHORT).show();
  267.                     Log.d("ACTION", ID);
  268.  
  269.                 } catch (Exception e) {
  270.                     e.printStackTrace();
  271.                     Toast.makeText(getBaseContext(), "Error on saving sample", Toast.LENGTH_SHORT).show();
  272.                     Config.voice_method = -1;
  273.                 } finally {
  274.                     if (samples_editor.commit())
  275.                         Toast.makeText(getBaseContext(), "Successfully saved sample!", Toast.LENGTH_SHORT).show();
  276.                     else
  277.                         Toast.makeText(getBaseContext(), "Error while adding sample to database", Toast.LENGTH_LONG).show();
  278.                     Config.voice_method = -1;
  279.                 }
  280.                 break;
  281.             }
  282.             case Constant.METHOD_TEST: {
  283.                 String s = "";
  284.                 s = data.getStringExtra(Constant.PREF_KEY_TMP_FILE);
  285.                 try {
  286.                     audioURL = new File(s).toURI().toURL();
  287.                 } catch (MalformedURLException e) {
  288.                     e.printStackTrace();
  289.                     Toast.makeText(con, "Malformed URL", Toast.LENGTH_SHORT).show();
  290.                     return;
  291.                 }
  292.                 doRecognition();
  293.                 try {
  294.                     AnalysisResult res = new AnalyzeTask().execute(ResultCollector.getList()).get();
  295.                     Log.d("ANALYSIS_RESULT", res.tag);
  296.                     Toast.makeText(getBaseContext(), "Testing", Toast.LENGTH_SHORT).show();
  297.                 } catch (InterruptedException e) {
  298.                     Toast.makeText(getBaseContext(), "Error while adding sample to database", Toast.LENGTH_LONG).show();
  299.                     e.printStackTrace();
  300.                 } catch (ExecutionException e) {
  301.                     Toast.makeText(getBaseContext(), "Error while adding sample to database", Toast.LENGTH_LONG).show();
  302.                     e.printStackTrace();
  303.                 } finally {
  304.  
  305.                     Config.voice_method = -1;
  306.                 }
  307.                 break;
  308.             }
  309.         }
  310.         super.onActivityResult(requestCode, resultCode, data);
  311.  
  312.     }
  313.  
  314.     /**
  315.      * Initialize all the Sphinx specific parameters which is used later
  316.      */
  317.     public void init_sphinx_params() throws IOException {
  318.         if (audioURL == null)
  319.             audioURL = new File("/sdcard/Download/hello.wav").toURI().toURL();
  320.  
  321.         Log.d("AUDIO_URL", audioURL.getFile());
  322.  
  323.         configURL = new File(getFilesDir().getPath() + "/config.xml").toURI().toURL();
  324.  
  325.         cm = new ConfigurationManager(configURL);
  326.         frontend = (FrontEnd) cm.lookup("epFrontEnd");
  327.         dataSource = (AudioFileDataSource) cm.lookup("audioFileDataSource");
  328.         dataSource.setAudioFile(audioURL, null);
  329.         isRecognizerInit = true;
  330.  
  331.     }
  332.  
  333.     class AnalyzeTask extends AsyncTask<LinkedList<FloatData>, Void, AnalysisResult> {
  334.  
  335.         ProgressDialog progressDialog;
  336.  
  337.         @Override
  338.         protected AnalysisResult doInBackground(LinkedList<FloatData>... params) {
  339.             LinkedList<FloatData> list = params[0];
  340.             AnalysisResult r = VoiceAnalyzer.getActionForVoice(list);
  341.             return r;
  342.         }
  343.  
  344.         @Override
  345.         protected void onPreExecute() {
  346.             progressDialog = new ProgressDialog(con);
  347.             progressDialog.setIndeterminate(true);
  348.             progressDialog.setMessage("Analyzing Voice Sample");
  349.             progressDialog.show();
  350.             super.onPreExecute();
  351.         }
  352.  
  353.         @Override
  354.         protected void onPostExecute(AnalysisResult aDouble) {
  355.             progressDialog.dismiss();
  356.             Toast.makeText(getBaseContext(), "Confidence: " + aDouble.res, Toast.LENGTH_LONG).show();
  357.             try {
  358.                 if (con != null) {
  359.                     Dialog d = new Dialog(con);
  360.                     d.setCancelable(true);
  361.                     d.setTitle("The max Match percentage is " + aDouble.res + "%! with tag: " + aDouble.tag);
  362.                     if ((aDouble.res) > 50.0 && action_map.containsKey(aDouble.tag)) {
  363.                         startApp(action_map.get(aDouble.tag));
  364.                         Toast.makeText(getBaseContext(), "Action " + aDouble.tag + " triggered", Toast.LENGTH_SHORT).show();
  365.                     } else {
  366.                         Toast.makeText(getBaseContext(), "No Trigger found!", Toast.LENGTH_SHORT).show();
  367.                     }
  368.                     Log.d("FILE_DELETE", "Deleted: " + audioURL.getFile());
  369.                     new File(audioURL.getPath()).delete();
  370.                     super.onPostExecute(aDouble);
  371.                 }
  372.             } catch (Exception e) {
  373.                 Log.e("ERROR ON TASK", e.getLocalizedMessage());
  374.                 Toast.makeText(getBaseContext(), "Error on running the analyzer task", Toast.LENGTH_SHORT).show();
  375.             }
  376.         }
  377.  
  378.         @Override
  379.         protected void onProgressUpdate(Void... values) {
  380.             super.onProgressUpdate(values);
  381.         }
  382.     }
  383. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement