Android Offline Speech Recognition to Display Only Word - android

I need help with android speech-text. Is it possible to display only the first word that was detected?like when the user inputs "the cat is playing" then the text that will only appear on the text box is the word "the".
The code that I used:
protected static final int RESULT_SPEECH = 1;
private Button btn_mic;
private TextView txtText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basic_level1);
txtText = (TextView) findViewById(R.id.txt);
btn_mic = (Button) findViewById(R.id.mic);
btn_mic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en-US");
try {
startActivityForResult(intent, RESULT_SPEECH);
txtText.setText("");
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(),
"Opps! Your device doesn't support Speech to Text",
Toast.LENGTH_SHORT);
t.show();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SPEECH: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtText.setText(text.get(0));
}
break;
}
}
}
}
thanks in advance. :)

ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if(text.size()>0){
String firstOne=text.get(0);
if(firstOne.contains(" ")){
String firstWord=firstOne.substring(0, firstOne.indexOf(' '));
txtText.setText(text.get(0));
}else{
txtText.setText(text.get(0));
}
}

Related

Making a message in Android Studio under a condition

i would like to make a message under a condition if the pronounciation is correct according to google assistant,
if my speaking is correct then there will be a message sayin' that my pronounciation is correct
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = etText.getText().toString();
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
});
btnSpeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mic_google = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mic_google.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mic_google.putExtra(RecognizerIntent.EXTRA_LANGUAGE, ID_BahasaIndonesia);
try {
startActivityForResult(mic_google, RESULT_SPEECH);
tvText.setText("");
}catch (ActivityNotFoundException e){
Toast.makeText(getApplicationContext(), "Maaf, Device Kamu Tidak Support Speech To Text", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case RESULT_SPEECH:
if (resultCode == RESULT_OK && data != null){
ArrayList<String> text = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
tvText.setText(text.get(0));
}
break;
}
}
}
here's my design now

How to get past information while converting speech to text in android?

As i am developing an android app and wants to convert speech into text, i am using built-in Google speech input activity to convert voice into text. I need past information but it continuously get cleared i got only current response. How need to handle same as google voice keyboard. As i talk it included to current String instep of clear.
MainActivity .java
public class MainActivity extends AppCompatActivity
{
private EditText txtSpeechInput;
private ImageButton btnSpeak;
private final int REQ_CODE_SPEECH_INPUT = 100;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtSpeechInput = findViewById(R.id.txtSpeechInput);
btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
btnSpeak.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
promptSpeechInput();
}
});
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));
intent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS, 20000000);
try
{
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
}
catch (ActivityNotFoundException a)
{
Toast.makeText(getApplicationContext(),
getString(R.string.speech_not_supported),
Toast.LENGTH_SHORT).show();
}
}
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)
{
final ArrayList<String> result= data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtSpeechInput.setText(result.get(0));
}
break;
}
}
}
If you only want to save one previously detected String, for this to achieve, you need to make a global String variable and store the value in that variable from results list.(Save the same String as you are setting on text view). But if you want to save all the strings, you need to make global String Arraylist and add all those string in that array list. Below is the code for that.
private EditText txtSpeechInput;
private ImageButton btnSpeak;
private final int REQ_CODE_SPEECH_INPUT = 100;
private List<String> previousStringList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
previousStringList = new ArrayList<>();
txtSpeechInput = findViewById(R.id.txtSpeechInput);
btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
btnSpeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
promptSpeechInput();
}
});
}
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));
intent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS, 20000000);
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
getString(R.string.speech_not_supported),
Toast.LENGTH_SHORT).show();
}
}
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) {
final ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtSpeechInput.setText(result.get(0));
if (result.get(0) != null) {
previousStringList.add(result.get(0));
}
}
break;
}
}
}
Hope that helps you.If you don't understand anything feel free to ask. If you don't want to save same String twice(already saved string), just replace below conditional line of code..
if (result.get(0) != null && !previousStringList.contains(result.get(0))) {
previousStringList.add(result.get(0));
}
The words get stored in Arraylists.
You can see an example of the implementation here, it works fine. The app stores the words, and then also performs the action requested.
https://github.com/saumyabahu/Travel-Safe/blob/master/MainActivity.java
public class MainActivity extends AppCompatActivity {
private SpeechRecognizer speechRecognizer;
private Intent intentRecognizer;
private EditText txtSpeechInput;
private ImageButton btnSpeak;
//this is the string in which words get stored and past strings with left to right cursor.
String previous = " ";
// ArrayList result = null;
private final int REQ_CODE_SPEECH_INPUT = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_main );
// ActivityCompat.requestPermissions( this, new String[]{Manifest.permission.RECORD_AUDIO}, PackageManager.PERMISSION_GRANTED );
txtSpeechInput = findViewById( R.id.ed );
btnSpeak = (ImageButton) findViewById( R.id.iButton );
btnSpeak.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
promptSpeechInput();
}
} );
}
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 ) );
intent.putExtra( RecognizerIntent.EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS, 20000000 );
try {
startActivityForResult( intent, REQ_CODE_SPEECH_INPUT );
} catch (ActivityNotFoundException a) {
Toast.makeText( getApplicationContext(),
getString( R.string.speech_not_supported ),
Toast.LENGTH_SHORT ).show();
}
}
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) {
final ArrayList<String> result = data
.getStringArrayListExtra( RecognizerIntent.EXTRA_RESULTS );
//this is the real problem.
txtSpeechInput.setText( previous + " " + result.get( 0 ) );
previous = txtSpeechInput.getText().toString();
txtSpeechInput.setText( previous );
}
break;
}
}
}
}

Keep mic on android speech to text

i want to mic on when i click on mic button and when again i click on mic button then it turn off.
i have a code kindly guide me how i keep mic on.
for example when i click mic button it start listening and when i click on mic again then it stop listening.
public class MainActivity extends AppCompatActivity {
private static final int REQ_CODE_SPEECH_INPUT = 100;
private TextView mVoiceInputTv;
private ImageButton mSpeakBtn;
private String[] myWords = {"start","stop","deactivate","activate","scan"};
private ArrayList<String> arrayList=new ArrayList<>();
boolean isStart;
String strings;
String start="start";
String stop="stop";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mVoiceInputTv = (TextView) findViewById(R.id.voiceInput);
mSpeakBtn = (ImageButton) findViewById(R.id.btnSpeak);
mSpeakBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mVoiceInputTv.setText("");
startVoiceInput();
}
});
}
private void startVoiceInput() {
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, "Hello, Please Speak somethings");
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
}
}
#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<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
TextView n=new TextView(this);
if (((result.get(0).toLowerCase()).contains(start))&&result.get(0).contains(stop)) {
strings = getBetweenStrings(result.get(0), start, stop);
mVoiceInputTv.setText("" + strings);
}
Log.d("action","String "+strings+ " result "+result.get(0)+" "+result.get(0).equals(myWords[0].toLowerCase()));
}
}
}
}
public static String getBetweenStrings(
String text,
String textFrom,
String textTo) {
String result = "";
result = text.substring(text.indexOf(textFrom) + textFrom.length(), text.length());
result = result.substring(0, result.indexOf(textTo));
return result;
}
}

Recognizer and Text to speech

I want to make an application in the way that when I speak, can answer me without the necessity of press any button. I want that my recordings guard on a string, and then depending of the record, the TTS can answer diferent things. This is my source code.
protected static final int RESULT_SPEACH =1;
private Button record, speak;
TextToSpeech t1;
String SpokedText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mai);
record = (Button) findViewById(R.id.record);
speak = (Button) findViewById(R.id.speak);
speak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reconize = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
try {
startActivityForResult(reconize, RESULT_SPEACH);
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(), "Your divece cannot execute this kind of operation", Toast.LENGTH_LONG);
t.show();
}
}
});
}
public void onActivityResult (int requestCode, int resultCode, Intent Data) {
super.onActivityResult(requestCode,resultCode,Data);
switch (requestCode) {
case RESULT_SPEACH: {
if (resultCode == RESULT_OK && null != Data) {
final String spoked = (RecognizerIntent.EXTRA_RESULTS);
if (spoked == "Good Morning") {
String SpokedText= "Good Morning";
t1.speak(SpokedText, TextToSpeech.QUEUE_FLUSH, null);
} else {
if (spoked== "I need your help") {
String SpokedText= "Alright sir";
t1.speak(SpokedText, TextToSpeech.QUEUE_FLUSH, null);
}
}
}
}
t1 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
t1.setLanguage(Locale.getDefault());
}
}
});
}}

How to get the result of voice recognition on EditBox?

I know there is like a ton topic and question regarding Voice Recognition and my question might be a stupid one too. but please bear with me guys.
I need to get the result of the speech recognition into an (Editable Text Box) instead of (Array List), the editable text box to allow the user to edit the result , just like a memo.
I found some questions like mine but I could not understand ,I am still a beginner comparing to you guys .
This is the code :
public class AVRScreen extends Activity {
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1001;
private ListView mlvTextMatches;
private Button mbtSpeak;
private Button reButton;
private EditText result;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.vr_screen);
Toast.makeText(this, "Press Speak! to Start Speeking",
Toast.LENGTH_LONG).show();
result = (EditText) findViewById(R.id.out_text);
mlvTextMatches = (ListView) findViewById(R.id.lvTextMatches);
mbtSpeak = (Button) findViewById(R.id.btSpeak);
reButton = (Button)findViewById(R.id.Replay1);
reButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
startActivity(new Intent(v.getContext(),KeyBoard.class));
}
});
checkVoiceRecognition();
}
public void checkVoiceRecognition() {
// Check if voice recognition is present
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() == 0) {
mbtSpeak.setEnabled(false);
mbtSpeak.setText("Voice recognizer not present");
Toast.makeText(this, "Voice recognizer not present",
Toast.LENGTH_SHORT).show();
}
}
public void speak(View view) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass()
.getPackage().getName());
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
//Start the Voice recognizer activity for the result.
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE)
//If Voice recognition is successful then it returns RESULT_OK
if(resultCode == RESULT_OK) {
ArrayList<String> textMatchList = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (textMatchList.get(0).contains("search")) {
} else {
// populate the Matches
mlvTextMatches .setAdapter(new ArrayAdapter<String>
(this,android.R.layout.simple_list_item_1,textMatchList));
}
}
//Result code for various error.
{
} if(resultCode == RecognizerIntent.RESULT_AUDIO_ERROR){
showToastMessage("Audio Error");
}else if(resultCode == RecognizerIntent.RESULT_CLIENT_ERROR){
showToastMessage("Client Error");
}else if(resultCode == RecognizerIntent.RESULT_NETWORK_ERROR){
showToastMessage("Network Error");
}else if(resultCode == RecognizerIntent.RESULT_NO_MATCH){
showToastMessage("No Match");
}else if(resultCode == RecognizerIntent.RESULT_SERVER_ERROR){
showToastMessage("Server Error");
}
super.onActivityResult(requestCode, resultCode, data);
}
/**
* Helper method to show the toast message
**/
void showToastMessage(String message){
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
This is the code after editing :
public class AVRScreen extends Activity {
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1001;
private Button mbtSpeak;
private Button reButton;
private EditText myEditText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.vr_screen);
Toast.makeText(this, "Press Speak! to Start Speeking",
Toast.LENGTH_LONG).show();
myEditText = (EditText) findViewById(R.id.out_text);
mbtSpeak = (Button) findViewById(R.id.btSpeak);
reButton = (Button)findViewById(R.id.Replay1);
reButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
startActivity(new Intent(v.getContext(),KeyBoard.class));
}
});
checkVoiceRecognition();
}
public void checkVoiceRecognition() {
// Check if voice recognition is present
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() == 0) {
mbtSpeak.setEnabled(false);
mbtSpeak.setText("Voice recognizer not present");
Toast.makeText(this, "Voice recognizer not present",
Toast.LENGTH_SHORT).show();
}
}
public void speak(View view) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass()
.getPackage().getName());
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
//Start the Voice recognizer activity for the result.
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE)
//If Voice recognition is successful then it returns RESULT_OK
if(resultCode == RESULT_OK) {
ArrayList<String> textMatchList = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (textMatchList.get(0).contains("search")) {
} else {
// populate the Matches
myEditText.setText(textMatchList.toString());
// if the above does not look good
// for (String match : textMatchList) {
// myEditText.append(match + "\n"); // or whatever separator you want
// }
}
}
the second try is :
} else {
// populate the Matches
//myEditText.setText(textMatchList.toString());
// if the above does not look good
for (String match : textMatchList) {
myEditText.append(match + "\n"); // or whatever separator you want
}
}
}
if(resultCode == RESULT_OK) {
ArrayList<String> textMatchList = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (textMatchList.get(0).contains("search")) {
} else {
// populate the Matches
result.setText(textMatchList.toString());
// if the above does not look good
// for (String match : textMatchList) {
// result.append(match + "\n"); // or whatever separator you want
// }
}

Categories

Resources