elvega
elvega

Reputation: 73

Recorder several audios in android

I need to record in the same activity several audios, everything works fine, but when I go to record an audio for the second or third time, the app stops and stops working. This is my code: What I can do to fix it?

public class CompromisoConVoz extends ActionBarActivity implements View.OnClickListener, MediaPlayer.OnCompletionListener {

private TextView valor1,valor2,valor3,valor1_1,valor2_2,valor3_3;
String Valor1,Valor2,Valor3;
MediaRecorder recorder;
MediaPlayer player;
File archivo;
String url1,url2,url3,url4,url5,url6;
private final int BUTTON_IDS[] = {
        R.id.resp1,
        R.id.resp1_1,
        R.id.resp2,
        R.id.resp2_2,
        R.id.resp3,
        R.id.resp3_3,
};

private Button Resp1,Resp1_1,Resp2,Resp2_2,Resp3,Resp3_3,parar1,parar1_1,parar2,parar2_2,parar3,parar3_3;
private Button Siguiente;




@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_compromiso_con_voz);

    //asignamos botones de grabación
    Resp1 =(Button) findViewById(BUTTON_IDS[0]);
    Resp1.setOnClickListener(this);
    Resp1_1 =(Button) findViewById(BUTTON_IDS[1]);
    Resp1_1.setOnClickListener(this);
    Resp2 =(Button) findViewById(BUTTON_IDS[2]);
    Resp2.setOnClickListener(this);
    Resp2_2 =(Button) findViewById(BUTTON_IDS[3]);
    Resp2_2.setOnClickListener(this);
    Resp3 =(Button) findViewById(BUTTON_IDS[4]);
    Resp3.setOnClickListener(this);
    Resp3_3 =(Button) findViewById(BUTTON_IDS[5]);
    Resp3_3.setOnClickListener(this);


    //asignamos botones de parada
    parar1 =(Button) findViewById(R.id.parar1);
    parar1.setOnClickListener(this);
    parar1_1 =(Button) findViewById(R.id.parar1_1);
    parar1_1.setOnClickListener(this);
    parar2 =(Button) findViewById(R.id.parar2);
    parar2.setOnClickListener(this);
    parar2_2 =(Button) findViewById(R.id.parar2_2);
    parar2_2.setOnClickListener(this);
    parar3 =(Button) findViewById(R.id.parar3);
    parar3.setOnClickListener(this);
    parar3_3=(Button) findViewById(R.id.parar3_3);
    parar3_3.setOnClickListener(this);


    valor1 = (TextView) findViewById(R.id.valor1);
    valor2 = (TextView) findViewById(R.id.valor2);
    valor3 = (TextView) findViewById(R.id.valor3);
    valor1_1 = (TextView) findViewById(R.id.valor1_1);
    valor2_2 = (TextView) findViewById(R.id.valor2_2);
    valor3_3= (TextView) findViewById(R.id.valor3_3);
    Log.d("prueba", "antes");
    //  SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences sharedPreferences = getSharedPreferences("MisPreferencias", Context.MODE_PRIVATE);
    //if(sharedPreferences.contains(CCCPreference.VALOR1)) {

    //Valor1 = sharedPreferences.getString(CCCPreference.VALOR1, CCCPreference.VALOR1);
    Valor1 = sharedPreferences.getString("valor1", "valor");
    Valor2 = sharedPreferences.getString("valor2", "valor");
    Valor3 = sharedPreferences.getString("valor3", "valor");



    Siguiente = (Button) findViewById(R.id.siguiente);

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

            if(url1.equals("") || url2.equals("") || url3.equals("") || url4.equals("") || url5.equals("") || url6.equals("")){
                Log.d("dentro","dentro");
                muestradialogo();
            }else{
                finish();
                Intent i= new Intent(CompromisoConVoz.this,CompromisoResultadoVoz.class);
                //i.putExtra("audio","resp1");
                i.putExtra("url1",url1);
                i.putExtra("url2",url2);
                i.putExtra("url3",url3);
                i.putExtra("url4",url4);
                i.putExtra("url5",url5);
                i.putExtra("url6",url6);
                startActivity(i);
                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);//las animaciones deben de estar en un directorio

            }

        }
    });

}


public void vibrate(int duration)
{
    Vibrator vibs = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    vibs.vibrate(duration);
}



@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.resp1:

            Resp1.setEnabled(false);
            parar1.setEnabled(true);
            url1=grabar(v, "resp1");
            break;

        case R.id.resp1_1:

            Resp1_1.setEnabled(false);
            parar1_1.setEnabled(true);
            url2=grabar(v, "resp1_1");
            break;

        case R.id.resp2:

            Resp2.setEnabled(false);
            parar2.setEnabled(true);

            url3=grabar(v, "resp2");

            break;
        case R.id.resp2_2:

            Resp2_2.setEnabled(false);
            parar2_2.setEnabled(true);
            url4=grabar(v, "resp2_2");
            break;

        case R.id.resp3:

            Resp3.setEnabled(false);
            parar3.setEnabled(true);
            url5=grabar(v, "resp3");
            break;

        case R.id.resp3_3:

            Resp3_3.setEnabled(false);
            parar3_3.setEnabled(true);
            url6=grabar(v, "resp3_3");
            break;
        case R.id.parar1:
            Resp1.setEnabled(true);
            parar1.setEnabled(false);
            detener(v);
            break;

        case R.id.parar1_1:
            Resp1_1.setEnabled(true);
            parar1_1.setEnabled(false);
            break;

        case R.id.parar2:
            Resp2.setEnabled(true);
            parar2.setEnabled(false);
            break;
        case R.id.parar2_2:
            Resp2_2.setEnabled(true);
            parar2_2.setEnabled(false);
            break;

        case R.id.parar3:
            Resp3.setEnabled(true);
            parar3.setEnabled(false);
            break;

        case R.id.parar3_3:
            Resp3_3.setEnabled(true);
            parar3_3.setEnabled(false);
            break;

        default:
            break;
    }
}

public String grabar(View v,String namefile) {

    String url;
    recorder = new MediaRecorder();
    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);//configura el micro del móvil como fuente
    recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);//formato audio salida
    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);//especifica el codel del audio
    File path = new File(Environment.getExternalStorageDirectory()//obtenemos el path de la sd y creamos un archivo de extensión 3gp
            .getPath());
    Log.d("uri1",path.toString());
    try {
        archivo = File.createTempFile(namefile, ".3gp", path);
    } catch (IOException e) {
        Log.d("uri1x","error");
    }

    url=archivo.toString();
    recorder.setOutputFile(archivo.getAbsolutePath());//donde se almacena

    try {//prepara la grabación
        recorder.prepare();
    } catch (IOException e) {
        Log.e("uri5", "error");
    }

    recorder.start();//graba

    return url;
}

public void detener(View v) {
    recorder.stop();
    recorder.release();
    recorder=null;

}

Console shows: 11-05 17:23:18.542 18916-18916/com.actua.actuaapp E/MediaRecorder: start failed: -38 11-05 17:23:18.542 18916-18916/com.actua.actuaapp D/AndroidRuntime: Shutting down VM 11-05 17:23:18.543 18916-18916/com.actua.actuaapp E/AndroidRuntime: FATAL EXCEPTION: main 11-05 17:23:18.543 18916-18916/com.actua.actuaapp E/AndroidRuntime: Process: com.actua.actuaapp, PID: 18916 11-05 17:23:18.543 18916-18916/com.actua.actuaapp E/AndroidRuntime: java.lang.IllegalStateException 11-05 17:23:18.543 18916-18916/com.actua.actuaapp E/AndroidRuntime: at android.media.MediaRecorder.start(Native Method) 11-05 17:23:18.543 18916-18916/com.actua.actuaapp E/AndroidRuntime: at com.actua.actuaapp.CompromisoConVoz.grabar(CompromisoConVoz.java:258) 11-05 17:23:18.543 18916-18916/com.actua.actuaapp E/AndroidRuntime: at com.actua.actuaapp.CompromisoConVoz.onClick(CompromisoConVoz.java:174) 11-05 17:23:18.543 18916-18916/com.actua.actuaapp E/AndroidRuntime: at android.view.View.performClick(View.java:4856) 11-05 17:23:18.543 18916-18916/com.actua.actuaapp E/AndroidRuntime: at android.view.View$PerformClick.run(View.java:19956) 11-05 17:23:18.543 18916-18916/com.actua.actuaapp E/AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:739) 11-05 17:23:18.543 18916-18916/com.actua.actuaapp E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:95) 11-05 17:23:18.543 18916-18916/com.actua.actuaapp E/AndroidRuntime: at android.os.Looper.loop(Looper.java:211) 11-05 17:23:18.543 18916-18916/com.actua.actuaapp E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5373) 11-05 17:23:18.543 18916-18916/com.actua.actuaapp E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method) 11-05 17:23:18.543 18916-18916/com.actua.actuaapp E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:372) 11-05 17:23:18.543 18916-18916/com.actua.actuaapp E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1020) 11-05 17:23:18.543 18916-18916/com.actua.actuaapp E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)

Upvotes: 0

Views: 93

Answers (2)

elvega
elvega

Reputation: 73

Thanks for your solution, but it does not work, so now my code, I find no fault, testing have seen the error is in the recorder.start line () when I have recorded several audio fails in this function.

my code:

public String grabar(View v,String namefile) {

    String url;
    recorder = new MediaRecorder();
    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);//configura el micro del móvil como fuente
    recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);//formato audio salida
    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);//especifica el codel del audio
    recorder.setAudioEncodingBitRate(16);
    recorder.setAudioSamplingRate(44100);
    recorder.setMaxDuration(20000);//graba máximo 20 segundos
    File path = new File(Environment.getExternalStorageDirectory()//obtenemos el path de la sd y creamos un archivo de extensión 3gp
            .getPath());
    Log.d("uri1",path.toString());
    try {
        archivo = File.createTempFile(namefile, ".3gp", path);
    } catch (IOException e) {
        Log.d("uri1x","error creando fichero");
    }
    Log.d("uri2",namefile);
    Log.d("uri3",archivo.toString());
    url=archivo.toString();
    recorder.setOutputFile(archivo.getAbsolutePath());//donde se almacena
    Log.d("uri4", archivo.getAbsolutePath().toString());
    try {//prepara la grabación
        recorder.prepare();
    } catch (IOException e) {
        Log.e("uri5", "Fallo en grabación");
    }
    Log.d("uri6", archivo.getAbsolutePath().toString());
    recorder.start();//graba
    Log.d("uri7", archivo.getAbsolutePath().toString());
    Toast.makeText(this, "Grabando...", Toast.LENGTH_SHORT).show();
  /*  tv1.setText("Grabando");
    b1.setEnabled(false);
    b2.setEnabled(true);*/
    isRecording = true;
    return url;
}

public void detener(View v) {
    if(isRecording) {
        isRecording=false;
        recorder.stop();
        recorder.reset();
        recorder = null;
        Toast.makeText(this, "Grabación terminada", Toast.LENGTH_SHORT).show();
    }
}@Override
public void onDestroy() {
    super.onDestroy();
    recorder.release();

}

Upvotes: 0

mylovemhz
mylovemhz

Reputation: 512

According to the documentation at: http://developer.android.com/reference/android/media/MediaRecorder.html

You have to use the reset() instead of release()

MediaRecorder recorder = new MediaRecorder();
 recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
 recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
 recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
 recorder.setOutputFile(PATH_NAME);
 recorder.prepare();
 recorder.start();   // Recording is now started
 ...
 recorder.stop();
 recorder.reset();   // You can reuse the object by going back to setAudioSource() step
 recorder.release(); // Now the object cannot be reused

If you want to record over and over. I would suggest changing your code so that you instanciate the recorder when the Activity is created, and you call recorder.release() when the activity is destroyed. Something like this:

public String grabar(View v,String namefile) {

    String url;
    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);//configura el micro del móvil como fuente
    recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);//formato audio salida
    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);//especifica el codel del audio
    File path = new File(Environment.getExternalStorageDirectory()//obtenemos el path de la sd y creamos un archivo de extensión 3gp
            .getPath());
    Log.d("uri1",path.toString());
    try {
        archivo = File.createTempFile(namefile, ".3gp", path);
    } catch (IOException e) {
        Log.d("uri1x","error");
    }

    url=archivo.toString();
    recorder.setOutputFile(archivo.getAbsolutePath());//donde se almacena

    try {//prepara la grabación
        recorder.prepare();
    } catch (IOException e) {
        Log.e("uri5", "error");
    }

    recorder.start();//graba

    isRecording = true;

    return url;
}

public void detener(View v) {
    if(isRecording){
        recorder.stop();
        recorder.reset();
        recorder=null;
    }
}

Also, be careful before you call your grabar() method. If the MediaRecorder is already recording because the user pressed one of the other buttons, then the recorder won't be ready to record a different file and you'll get an IllegalStateException. You'll have to stop the current one, so I added a boolean that keeps track of the state of the recorder. When the user clicks a record button. Check if it's recording, if it is, stop recording. Then start the new one.

Upvotes: 1

Related Questions