1

Tengo un problema. Tengo una aplicación en la que solicito los permisos para grabar audio. El problema es que los solicito una vez que pulso el botón de grabar pero después tengo que volver a pulsar para que grabe, yo lo que quiero es pulsar el botón, me solicite los permisos y ya grabe sin tener que volver a pulsar. El código es el siguiente:

public class MainActivity extends AppCompatActivity {

    private static final int MY_PERMISSIONS_RECORD_AUDIO = 1;
    SpeechRecognizer mSpeechRecognizer;
    Intent mSpeechRecognizerIntent;
    @BindView(R.id.etBeforeTranslate)
    EditText etBeforeTranslate;
    @BindView(R.id.ivLogo)
    ImageView ivLogo;
    @BindView(R.id.btnTranslate)
    Button btnTranslate;
    @BindView(R.id.btnVoice)
    ImageButton btnVoice;

    private DatabaseReference Translates;

    public String removeAccents() {...}

    public String textTranslate() {...}

    public void registerTranslates() {...}

    private void checkPermission() {

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, MY_PERMISSIONS_RECORD_AUDIO);
        }

    }

    private void speechToText(){

        checkPermission();

        mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
        mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());

        mSpeechRecognizer.setRecognitionListener(new RecognitionListener() {
            @Override
            public void onReadyForSpeech(Bundle params) {

            }

            @Override
            public void onBeginningOfSpeech() {

            }

            @Override
            public void onRmsChanged(float rmsdB) {

            }

            @Override
            public void onBufferReceived(byte[] buffer) {

            }

            @Override
            public void onEndOfSpeech() {

            }

            @Override
            public void onError(int error) {

            }

            @Override
            public void onResults(Bundle results) {
                ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
                if (matches != null) {
                    etBeforeTranslate.setText(matches.get(0));

                }
            }

            @Override
            public void onPartialResults(Bundle partialResults) {

            }

            @Override
            public void onEvent(int eventType, Bundle params) {

            }
        });
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);



        btnVoice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                speechToText();
                mSpeechRecognizer.startListening(mSpeechRecognizerIntent);

            }
        });

        btnTranslate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String texto = textTranslate();

                if (etBeforeTranslate.getText().toString().trim().isEmpty()) {

                    ivLogo.setImageResource(R.drawable.logotipoangry);
                    Toast.makeText(MainActivity.this, "¡Ay que agobio! Intridici il tixti, anda", Toast.LENGTH_SHORT).show();

                } else {

                    Translates = FirebaseDatabase.getInstance().getReference("Translates");
                    registerTranslates();
                    ivLogo.setImageResource(R.drawable.logotipo);
                    Intent intent = new Intent(MainActivity.this, TranslateActivity.class);
                    intent.putExtra("texto", texto);
                    startActivity(intent);

                }

            }
        });

    }

}

A ver, se que una solución sería pedirlos nada más iniciar la aplicación, pero quiero pedirlos justo al pulsar el botón pero que acto seguido ya grabe la voz.

8
  • AudioRuntimePermissions. Prácticamente seria invocar el método que realiza la grabación una vez que los permisos sean concebidos.
    – YemisiSCG
    Commented el 10 jul. 2019 a las 15:29
  • Osea utilizar mi speechToText() al final del propio método de solicitar permisos?
    – Ludiras
    Commented el 10 jul. 2019 a las 15:39
  • Así es. Utiliza un condicional, solo si te dan los permisos invocas directamente tu speechToText().
    – YemisiSCG
    Commented el 10 jul. 2019 a las 15:45
  • Tengo un problema, y es que no se donde colocar la linea mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
    – Ludiras
    Commented el 10 jul. 2019 a las 16:29
  • En tu checkPermission() yo colocaria algo así: if(ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) { //Go ahead with recording audio now speechToText(); }
    – YemisiSCG
    Commented el 10 jul. 2019 a las 16:53

1 respuesta 1

1

Lo he resuelto así, por si a alguien le sirve, dejo el código completo, si alguien ve alguna forma más eficiente, soy todo ojos:

    package com.isaac.tiquismiquis;

import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.util.ArrayList;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {

    private static final int MY_PERMISSIONS_RECORD_AUDIO = 1;
    SpeechRecognizer mSpeechRecognizer;
    Intent mSpeechRecognizerIntent;
    @BindView(R.id.etBeforeTranslate)
    EditText etBeforeTranslate;
    @BindView(R.id.ivLogo)
    ImageView ivLogo;
    @BindView(R.id.btnTranslate)
    Button btnTranslate;
    @BindView(R.id.btnVoice)
    ImageButton btnVoice;

    private DatabaseReference Translates;

    public String removeAccents() {

        String accent = etBeforeTranslate.getText().toString();

        String withoutAccent = accent.replace("Á", "A")
                .replace("É", "E")
                .replace("Í", "I")
                .replace("Ó", "O")
                .replace("Ú", "U")
                .replace("á", "a")
                .replace("é", "e")
                .replace("í", "i")
                .replace("ó", "o")
                .replace("ú", "u");

        return withoutAccent;
    }

    public String textTranslate() {

        String text = removeAccents();

        String translateText = text.replace("a", "i")
                .replace("e", "i")
                .replace("o", "i")
                .replace("u", "i")
                .replace("A", "I")
                .replace("E", "I")
                .replace("O", "I")
                .replace("U", "I");

        return translateText;

    }

    public void registerTranslates() {
        String beforeTranslate = etBeforeTranslate.getText().toString();
        String afterTranslate = textTranslate().toString();

        String id = Translates.push().getKey();
        Translates traducciones = new Translates(id, beforeTranslate, afterTranslate);
        Translates.child("Translates").child(id).setValue(traducciones);
    }

    private void checkPermission() {

        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.RECORD_AUDIO)
                != PackageManager.PERMISSION_GRANTED) {

            //When permission is not granted by user, show them message why this permission is needed.
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.RECORD_AUDIO)) {
                                //Give user option to still opt-in the permissions
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.RECORD_AUDIO},
                        MY_PERMISSIONS_RECORD_AUDIO);

            } else {
                // Show user dialog to grant permission to record audio
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.RECORD_AUDIO},
                        MY_PERMISSIONS_RECORD_AUDIO);
            }
        }
        //If permission is granted, then go ahead recording audio
        else if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.RECORD_AUDIO)
                == PackageManager.PERMISSION_GRANTED) {

            //Go ahead with recording audio now
            speechToText();
        }

    }

    private void speechToText() {

        mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
        mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());

        mSpeechRecognizer.setRecognitionListener(new RecognitionListener() {
            @Override
            public void onReadyForSpeech(Bundle params) {

            }

            @Override
            public void onBeginningOfSpeech() {

            }

            @Override
            public void onRmsChanged(float rmsdB) {

            }

            @Override
            public void onBufferReceived(byte[] buffer) {

            }

            @Override
            public void onEndOfSpeech() {

            }

            @Override
            public void onError(int error) {

            }

            @Override
            public void onResults(Bundle results) {
                ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
                if (matches != null) {
                    etBeforeTranslate.setText(matches.get(0));

                }
            }

            @Override
            public void onPartialResults(Bundle partialResults) {

            }

            @Override
            public void onEvent(int eventType, Bundle params) {

            }
        });

        mSpeechRecognizer.startListening(mSpeechRecognizerIntent);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_RECORD_AUDIO: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // permission was granted, yay!
                    speechToText();
                } else {
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(this, "Vaya, pues te quedas sin hablarme", Toast.LENGTH_LONG).show();
                }
                return;
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);


        btnVoice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                checkPermission();
                speechToText();
            }
        });

        btnTranslate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String texto = textTranslate();

                if (etBeforeTranslate.getText().toString().trim().isEmpty()) {

                    ivLogo.setImageResource(R.drawable.logotipoangry);
                    Toast.makeText(MainActivity.this, "¡Ay que agobio! Intridici il tixti, anda", Toast.LENGTH_SHORT).show();

                } else {

                    Translates = FirebaseDatabase.getInstance().getReference("Translates");
                    registerTranslates();
                    ivLogo.setImageResource(R.drawable.logotipo);
                    Intent intent = new Intent(MainActivity.this, TranslateActivity.class);
                    intent.putExtra("texto", texto);
                    startActivity(intent);


                }

            }
        });

    }

}

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.