import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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.util.ArrayList;
import java.util.Locale;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
String choice, choice2, langlocale;
TextToSpeech speak_button;
SpeechRecognizer record;
Intent text_button;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater seeMenu = getMenuInflater();
seeMenu.inflate(R.menu.menu_main, menu);
return true;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner pick = (Spinner) findViewById(R.id.input);
pick.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView adapterView, View view, int i, long l) {
switch(i){
case 0:
choice = "en";
break;
case 1:
choice = "fr";
break;
case 2:
choice = "it";
break;
case 3:
choice = "de";
break;
case 4:
choice = "zh-TW";
break;
case 5:
choice = "es";
break;
}
}
@Override
public void onNothingSelected(AdapterView adapterView) {
}
});
Spinner ret = (Spinner) findViewById(R.id.output);
ret.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView adapterView, View view, int i, long l) {
switch(i){
case 0:
choice2 = "en";
break;
case 1:
choice2 = "fr";
break;
case 2:
choice2 = "it";
break;
case 3:
choice2 = "de";
break;
case 4:
choice2 = "zh-CN";
break;
case 5:
choice2 = "es";
break;
}
}
@Override
public void onNothingSelected(AdapterView adapterView) {
}
});
//Enable text to sppech button
Button speak = (Button) findViewById(R.id.text2sp);
speak.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final TextView run = (TextView) findViewById(R.id.textView);
//Toast.makeText(getApplicationContext(), run.getText().toString(),Toast.LENGTH_SHORT).show();
speak_button = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR) {
speak_button.setLanguage(Locale.US);
}
//switch case for language
switch(choice2){
case "en":
speak_button.setLanguage(Locale.ENGLISH);
break;
case "fr":
speak_button.setLanguage(Locale.FRENCH);
break;
case "it":
speak_button.setLanguage(Locale.ITALIAN);
break;
case "de":
speak_button.setLanguage(Locale.GERMAN);
break;
case "zh-CN":
speak_button.setLanguage(Locale.CHINESE);
break;
case "es":
choice2 = "es";
break;
}
//speak_button.setLanguage(new Locale(langlocale));
speak_button.speak(run.getText().toString(), TextToSpeech.QUEUE_FLUSH, null, UUID.randomUUID().toString());
}
});;
}
});
Button text = (Button) findViewById(R.id.sp2text);
record = SpeechRecognizer.createSpeechRecognizer(this);
record.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) {
ArrayList
EditText show = (EditText) findViewById(R.id.editText);
show.setText(print.get(0));
}
@Override
public void onPartialResults(Bundle bundle) {
}
@Override
public void onEvent(int i, Bundle bundle) {
}
});
text.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
text_button = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
text_button.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE, Locale.getDefault());
text_button.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass().getPackage().getName());
text_button.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
text_button.putExtra(RecognizerIntent.EXTRA_PROMPT, "Please speak into the microphone");
try {
startActivityForResult(text_button, 100);
//record.startListening(text_button);
}catch(ActivityNotFoundException nf)
{
Toast.makeText(getApplicationContext(), "An error occured during recording", Toast.LENGTH_LONG).show();
}
//record.startListening(text_button);
}
public void OnActivityResult(int request, int result, Intent data){
if(request == 100 && result == RESULT_OK && data != null){
ArrayList
EditText show = (EditText) findViewById(R.id.editText);
show.setText(print.get(0));
}
}
});
// Get the location manager
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String provider;
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
//Location location = locationManager.getLastKnownLocation(provider);
}
@Override
public void onPause(){
if(speak_button !=null){
speak_button.stop();
speak_button.shutdown();
}
super.onPause();
}
@Override
//Method for when menu buttons are pressed
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// When the user clicks FETCH, fetch the first 500 characters of
// raw HTML from www.google.com.
case R.id.fetch_action:
EditText read = (EditText) findViewById(R.id.editText);
TextView write = (TextView) findViewById(R.id.textView);
//Sections for google translate api
Uri.Builder urlbuilder = new Uri.Builder();
urlbuilder.scheme("https")
.authority("www.googleapis.com")
.appendPath("language")
.appendPath("translate")
.appendPath("v2")
.appendQueryParameter("q", read.getText().toString())
.appendQueryParameter("target", choice2)
.appendQueryParameter("format", "text")
.appendQueryParameter("source", choice)
.appendQueryParameter("key", "Google API Key");
//Call another process for web communication
new getFromSite().execute(urlbuilder.build().toString());
//write.setText(return_string.readLine());
return true;
// Clear the log view fragment.
case R.id.clear_action:
//Erase text fields
read = (EditText) findViewById(R.id.editText);
read.setText("");
write = (TextView) findViewById(R.id.textView);
write.setText("");
return true;
}
return false;
}
/**
* This was adapted from teh network connect app
*
* Implementation of AsyncTask, to fetch the data in the background away from
* the UI thread.
*/
private class getFromSite extends AsyncTask
@Override
protected String doInBackground(String... urls) {
try {
return loadFromNetwork(urls[0]);
} catch (IOException e) {
return getString(R.string.connection_error);
}
}
/**
* Uses the logging framework to display the output of the fetch
* operation in the log fragment.
*/
@Override
protected void onPostExecute(String result) {
TextView write = (TextView) findViewById(R.id.textView);
//JsonReader print = new JsonReader(result);
try {
JSONObject parse = new JSONObject(result);
JSONObject next = parse.getJSONObject("data");
JSONArray array = next.optJSONArray("translations");
JSONObject ret = array.getJSONObject(0);
write.setText(ret.optString("translatedText").toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
/** Initiates the fetch operation. */
private String loadFromNetwork(String urlString) throws IOException {
InputStream stream = null;
String str ="";
try {
stream = downloadUrl(urlString);
str = readIt(stream, 500);
} finally {
if (stream != null) {
stream.close();
}
}
return str;
}
/**
* Given a string representation of a URL, sets up a connection and gets
* an input stream.
* @param urlString A string representation of a URL.
* @return An InputStream retrieved from a successful HttpURLConnection.
* @throws java.io.IOException
*/
private InputStream downloadUrl(String urlString) throws IOException {
// BEGIN_INCLUDE(get_inputstream)
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Start the query
conn.connect();
InputStream stream = conn.getInputStream();
return stream;
// END_INCLUDE(get_inputstream)
}
/** Reads an InputStream and converts it to a String.
* @param stream InputStream containing HTML from targeted site.
* @param len Length of string that this method returns.
* @return String concatenated according to len parameter.
* @throws java.io.IOException
* @throws java.io.UnsupportedEncodingException
*/
private 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);
}
}
No comments:
Post a Comment
Thank you very much for viewing this entry and I hope you are able to return soon to continue to enjoy more of the site.
Please share your thoughts in the comment section.
Be blessed and enjoy life!