activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Speach To Text Example"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="@+id/speakButton"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="30dp"
android:text="Speak" />
<TextView
android:id="@+id/displayTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="30dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
MainActivity.java:
package com.ram.speechtotext;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView displayText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
displayText = (TextView) findViewById(R.id.displayTextView);
Button speakButton = (Button) findViewById(R.id.speakButton);
speakButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent in = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
in.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
try {
startActivityForResult(in, 1);
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(
getApplicationContext(),
"sorry, your device doesn't support speech to text feature",
Toast.LENGTH_LONG).show();
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == 1) {
if (resultCode == RESULT_OK && data != null) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
displayText.setText(text.get(0));
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
No comments:
Post a Comment