package info.androidhive.speechtotext; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Locale; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.speech.RecognizerIntent; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { private TextView txtSpeechInput; private ImageButton btnSpeak; private final int REQ_CODE_SPEECH_INPUT = 100; private final int REQ_PREF = 200; public static final String TAG = MainActivity.class.getSimpleName(); public static final int MAX_ANSWER_LEN = 500; public static String Url; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txtSpeechInput = (TextView) findViewById(R.id.txtSpeechInput); btnSpeak = (ImageButton) findViewById(R.id.btnSpeak); // hide the action bar //getActionBar().hide(); btnSpeak.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { promptSpeechInput(); } }); new SilentTalkToMeTask().execute("goodbye"); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); Url = preferences.getString(SettingsActivity.KEY_PREF_SERVER_URL, ""); Log.d(TAG, "Server url is " + Url); } /** * Showing google speech input dialog * */ private void promptSpeechInput() { Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault()); intent.putExtra(RecognizerIntent.EXTRA_PROMPT, getString(R.string.speech_prompt)); try { startActivityForResult(intent, REQ_CODE_SPEECH_INPUT); } catch (ActivityNotFoundException a) { Toast.makeText(getApplicationContext(), getString(R.string.speech_not_supported), Toast.LENGTH_SHORT).show(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQ_CODE_SPEECH_INPUT: { if (resultCode == RESULT_OK && null != data) { ArrayList result = data .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); txtSpeechInput.setText(result.get(0)); ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { new TalkToMeTask().execute(result.get(0)); } else { txtSpeechInput.setText("No network connection available."); } } break; } case REQ_PREF:{ SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); Url = preferences.getString(SettingsActivity.KEY_PREF_SERVER_URL, ""); } break; } } @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 boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_settings: startActivityForResult(new Intent(getBaseContext(), SettingsActivity.class), REQ_PREF); return true; } return super.onOptionsItemSelected(item); } private class TalkToMeTask extends AsyncTask{ @Override protected String doInBackground(String... question) { try { return talkToServer(question[0]); } catch (IOException e){ Log.d(TAG, e.toString()); return "Cannot connect to server"; } } @Override protected void onPostExecute(String s) { txtSpeechInput.setText(s); } } private class SilentTalkToMeTask extends AsyncTask{ @Override protected String doInBackground(String... question) { try { return talkToServer(question[0]); } catch (IOException e){ Log.d(TAG, e.toString()); return "Cannot connect to server"; } } @Override protected void onPostExecute(String s) { } } private String talkToServer(String question) throws IOException { InputStream is = null; try { URL url = new URL(Url); String urlParameters = "msg="+question; byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 ); int postDataLength = postData.length; HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput( true ); conn.setInstanceFollowRedirects( false ); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("charset", "utf-8"); conn.setRequestProperty( "Content-Length", Integer.toString( postData.length )); conn.setUseCaches(false); DataOutputStream wr = new DataOutputStream( conn.getOutputStream()); wr.write(postData); conn.connect(); int response = conn.getResponseCode(); Log.d(TAG, "The response is: " + response); is = conn.getInputStream(); String contentAsString = readIt(is, MAX_ANSWER_LEN); return contentAsString; } finally { if (is != null){ is.close(); } } } // Reads an InputStream and converts it to a String. public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException { Reader reader = null; reader = new InputStreamReader(stream, "UTF-8"); char[] buffer = new char[len]; reader.read(buffer); return new String(buffer); } }