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;
}
}
Related
I am trying to add an image from the gallery to an image view. It has been added but the image is disappearing from the image view on rotating the screen. The image has been saved to firebase. How to save the activity state? I have searched for it but did not find the relevant answer.Can anyone help me out to solve the problem.
public class skcreateac extends AppCompatActivity
{
static final int PICK_IMAGE_REQUEST = 1;
private EditText sketac1;
private EditText sksetac1;
private EditText sketac2;
private EditText sketac3;
private EditText sketac4;
private EditText sketac5;
private Button skbt;
private Spinner spac;
private ImageView skimg;
private StorageReference skdbimg, fp;
private Firebase skrootac1;
private String strsk, skurl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_skcreateac);
spac = (Spinner)findViewById(R.id.spinner2);
String cities[] = new String[]{"Hyderabad", "Warangal"};
ArrayAdapter<String> cityadapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, cities);
spac.setAdapter(cityadapter);
skimg = (ImageView) findViewById(R.id.skimg);
skdbimg = FirebaseStorage.getInstance().getReference();
sketac1 = (EditText) findViewById(R.id.skonac);
sksetac1 = (EditText) findViewById(R.id.sksncac);
sketac2 = (EditText) findViewById(R.id.skphcac);
sketac3 = (EditText) findViewById(R.id.sksaddress);
sketac4 = (EditText) findViewById(R.id.skpwcac);
sketac5 = (EditText) findViewById(R.id.skpwrcac);
skbt = (Button) findViewById(R.id.bsu);
strsk = getIntent().getExtras().getString("value");
String url1 = "https://my-app2-a14eb.firebaseio.com/Shopkeepers/";
String url2 = strsk;
skurl = url1 + url2;
skrootac1 = new Firebase(skurl);
skimg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent skimg = new Intent(Intent.ACTION_PICK);
skimg.setType("image/*");
startActivityForResult(skimg, PICK_IMAGE_REQUEST);
}
});
skbt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s1 = sketac1.getText().toString();
if (sketac1.getText().length() == 0) {
sketac1.setError("Kindly enter your Name");
}
Firebase childac1 = skrootac1.child("Name");
childac1.setValue(s1);
String ss1 = sksetac1.getText().toString();
if (sksetac1.getText().length() == 0) {
sksetac1.setError("Kindly enter your ShopName");
}
Firebase childsac1 = skrootac1.child("ShopName");
childsac1.setValue(ss1);
String s2 = sketac2.getText().toString();
long i = Long.parseLong(s2);
int j = 0;
while (i > 0) {
i = i / 10;
j++;
}
if (j == 10) {
Firebase childac2 = skrootac1.child("Phone");
childac2.setValue(s2);
} else {
Toast.makeText(skcreateac.this, "Enter valid Mobile number", Toast.LENGTH_LONG).show();
}
String s3 = spac.getSelectedItem().toString();
Firebase childac3 = skrootac1.child("City");
childac3.setValue(s3);
String s4 = sketac3.getText().toString();
Firebase childac4 = skrootac1.child("Address");
childac4.setValue(s4);
String s5 = sketac4.getText().toString();
String s6 = sketac5.getText().toString();
if (s5.equals(s6)) {
Firebase childac5 = skrootac1.child("Password");
childac5.setValue(s5);
} else {
Toast.makeText(skcreateac.this, "Confirm Password field doesnot match with Create Password field", Toast.LENGTH_LONG).show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK) {
final Uri uri = data.getData();
fp = skdbimg.child("SKPhotos").child(strsk);
fp.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Picasso.get().load(uri).fit().centerCrop().into(skimg);
Toast.makeText(skcreateac.this, "Uploaded photo", Toast.LENGTH_LONG).show();
}
});
}
}
Add following -
#Override
protected void onSaveInstanceState (Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("outputFileUri", photoURI);
}
Make a private URI photoURI = null; in your activity.
Then in your onCreate() add do
#Override
protected void onCreate(Bundle savedInstanceState){
// your other codes
skrootac1 = new Firebase(skurl);
// your other codes
if (savedInstanceState != null)
{
photoURI= savedInstanceState.getParcelable("outputFileUri");
setImage(photoURI);
}
}
private void setImage(final Uri uri){
fp = skdbimg.child("SKPhotos").child(strsk);
fp.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Picasso.get().load(uri).fit().centerCrop().into(skimg);
Toast.makeText(skcreateac.this, "Uploaded photo", Toast.LENGTH_LONG).show();
}
});
}
And finally, change your onActivityResult()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK) {
photoURI = data.getData();
setImage(photoURI);
}
}
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;
}
}
}
}
After sending email, I need to go other activity. But I'm going to next activity before sending email. the same question having answer that tells to use startactivityforresult.bt I'm new to Android. I don't know how to use that.
public class GetQuoteact extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private ProgressDialog loadDialog;
Button btsub;
private String mobilee, namee, emailide, statee, citye, pine, subjecte, streete, success,endresp;
EditText name_c, mobile_c, emailid_c, state_c, city_c, street_c, pin_c, subject_c;
public String batter_feat_id,Modelname,Batterytype = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
// requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_getquote2);
if (getIntent().getBooleanExtra("EXIT", false)) {
finish();
}
name_c = (EditText) findViewById(R.id.name);
mobile_c = (EditText) findViewById(R.id.mobile);
emailid_c = (EditText) findViewById(R.id.email_id);
state_c = (EditText) findViewById(R.id.state);
city_c = (EditText) findViewById(R.id.city);
street_c = (EditText) findViewById(R.id.street);
pin_c = (EditText) findViewById(R.id.pincode);
subject_c = (EditText) findViewById(R.id.subject);
btsub = (Button) findViewById(R.id.bt_sub);
Intent in1 = getIntent();
batter_feat_id = in1.getStringExtra("battery_featuer_idc");
Modelname = in1.getStringExtra("Model_name");
Batterytype = in1.getStringExtra("Battery_type");
btsub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
inilize();
try {
if (!validate()) {
Toast.makeText(GetQuoteact.this, "Enter necessary details!!!", Toast.LENGTH_SHORT).show();
} else {
showDialog();
onfetch(batter_feat_id);}
} catch (Exception e) {
Toast.makeText(GetQuoteact.this, "" + e, Toast.LENGTH_SHORT).show();
}
}
});
}
public void inilize() {
namee = name_c.getText().toString();
mobilee = mobile_c.getText().toString();
emailide = emailid_c.getText().toString();
statee = state_c.getText().toString();
citye = city_c.getText().toString();
pine = pin_c.getText().toString();
subjecte = subject_c.getText().toString();
streete = street_c.getText().toString();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
Intent intent=new Intent(getApplicationContext(),Lastpage.class);
startActivity(intent);
}
else{
Toast.makeText(GetQuoteact.this, "error on sending mail...", Toast.LENGTH_SHORT).show();
}
}
private void onfetch(String batter_feat_id) {
Intent ithh =new Intent(Intent.ACTION_SENDTO);
ithh.setData(Uri.parse("mailto:"));
String[] to={"abc#gmail.com"};
ithh.putExtra(ithh.EXTRA_EMAIL,to);
ithh.putExtra(ithh.EXTRA_SUBJECT,"Email From JC APP");
ithh.putExtra(ithh.EXTRA_TEXT,"Model Name :"+Modelname
+"\nBattery Type:"+Batterytype
+"\nName :"+namee
+"\nContact no :"+mobilee
+"\nmailid="+emailide
+"\nstate="+statee
+"\ncity="+citye
+"\narea="+streete
+"\npincode="+pine
+"\nsubject="+subjecte);
startActivityForResult(ithh.createChooser(ithh,"Sent!!!"),1);
}
else{
Toast.makeText(GetQuoteact.this, "error!!! ", Toast.LENGTH_SHORT).show();
}
}
}
change your onActivityResult to something like this
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//autocompleteFragment.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
// success open your activity
}
}
}
I hope this helps
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());
}
}
});
}}
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));
}
}