我制作的音频文件没有显示或者没有创建。

时间:2018-04-05 17:22:21

标签: java android

该应用程序的目的是从外部或内部的麦克风录制音频,无论如何,但音频文件未正确创建或保存。我不知道为什么,但它让我疯了。

感谢您的帮助。

这是主要的活动代码(如果您需要更多内容,例如清单代码,请询问它,我会将其包括在内):

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.view.View;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class MainActivity extends AppCompatActivity {

    private TextView mTextMessage;
    private Chronometer c;
    private ImageButton _record, _pause, _stop;
    private MediaRecorder recorder;
    MediaPlayer player;
    private File archivo;
    private File archivo_final;
    private boolean estadoGrab;
    private String m_Text = "";
    long mLastStopTime = 0;
    final Context context = this;
    int number_of_recordings;
    private static final int  MY_PERMISSIONS_REQUEST_RECORD_AUDIO = 0;
    private static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 0;
    private static final int MY_PERMISSIONS_REQUEST_WRITE_INTERNAL_STORAGE = 0;



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

        mTextMessage = (TextView) findViewById(R.id.message);

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

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.RECORD_AUDIO)) {

                // Show an expanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.

            } else {

                // No explanation needed, we can request the permission.
                if(ContextCompat.checkSelfPermission(this,
                        Manifest.permission.RECORD_AUDIO)
                        != PackageManager.PERMISSION_GRANTED){
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.RECORD_AUDIO},
                            MY_PERMISSIONS_REQUEST_RECORD_AUDIO);}
                if(ContextCompat.checkSelfPermission(this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE )
                        != PackageManager.PERMISSION_GRANTED){
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE },
                            MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE );}


            }


        }

        c = (Chronometer)findViewById(R.id.duration);
        _record = (ImageButton) findViewById(R.id.Record);
        _stop = (ImageButton) findViewById(R.id.Stop);
        _pause = (ImageButton) findViewById(R.id.Pause);
        //mostramos los botones que hagan falta en el momento dado
        _record.setEnabled(true);
        _pause.setEnabled(false);
        _stop.setEnabled(false);


        estadoGrab=true;
        number_of_recordings = 0;

    }

    public void grabar(View v){
        //Iniciamos la "grabadora" para grabar por microfono en formato MPGE_4 y con codificarlo con el algoritmo AMR_NB

        if(estadoGrab) {

            recorder = new MediaRecorder();
            recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

                File folder = new File(context.getFilesDir().getAbsolutePath());


                if(folder.exists())
                    Toast.makeText(getApplicationContext(), context.getFilesDir().toString(), Toast.LENGTH_LONG).show();
                folder.mkdir();

                String path = folder.getAbsolutePath();

                number_of_recordings = folder.listFiles().length;
                try {
                    archivo = new File(folder.getAbsolutePath(), "Recording_" + number_of_recordings + ".3gp");
                } catch (Exception ex) {


                }

                recorder.setOutputFile(archivo.getAbsolutePath());

                try {
                    recorder.prepare();
                } catch (IOException ex) {

                }

                recorder.start();

                // on first start
                if (mLastStopTime == 0)
                    c.setBase(SystemClock.elapsedRealtime());

                c.start();
                _pause.setVisibility(View.VISIBLE);
                _stop.setVisibility(View.VISIBLE);
                _record.setVisibility(View.INVISIBLE);
                _record.setEnabled(false);
                _pause.setEnabled(true);
                _stop.setEnabled(true);
            }else{
                System.out.println("Que no se puede acceder a la sd pixa");}
            } else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

                    long intervalOnPause = (SystemClock.elapsedRealtime() - mLastStopTime);
                    c.setBase(c.getBase() + intervalOnPause);
                    recorder.resume();
                    c.start();
                    _pause.setEnabled(true);
                    _pause.setVisibility(View.VISIBLE);
                    _record.setVisibility(View.INVISIBLE);
                    _record.setEnabled(false);
                    estadoGrab = true;
                }
            }

        }




    public void pause(View v){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            recorder.pause();
            estadoGrab=false;
        }

        c.stop();
        mLastStopTime = SystemClock.elapsedRealtime();


        _record.setVisibility(View.VISIBLE);
        _pause.setVisibility(View.INVISIBLE);
        _record.setEnabled(true);
        _pause.setEnabled(false);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public void stop(View v){


        c.stop();
        mLastStopTime = SystemClock.elapsedRealtime();


        mLastStopTime = 0;
        AlertDialog.Builder builder;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            builder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert);
        } else {
            builder = new AlertDialog.Builder(this);
        }

        builder.setTitle("Grabación Finalizada")
                .setMessage("¿Desea guardar la grabación?")
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        recorder.stop();
                        recorder.release();
                        recorder = null;
                        dialog.cancel();

                        // custom dialog
                        AlertDialog.Builder name_setter = new AlertDialog.Builder(context);
                        name_setter.setTitle("Nombre del archivo");

                        final EditText name_input = new EditText(context);
                        name_input.setInputType(InputType.TYPE_CLASS_TEXT);
                        name_input.setText("Recording_"+number_of_recordings+".mp3");

                        name_setter.setView(name_input);

                        name_setter.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                m_Text = name_input.getText().toString();
                                archivo_final = new File(archivo.getAbsolutePath(), m_Text);

                                try (InputStream in = new FileInputStream(archivo)) {
                                    try (OutputStream out = new FileOutputStream(archivo_final)) {
                                        // Transfer bytes from in to out
                                        byte[] buf = new byte[1024];
                                        int len;
                                        while ((len = in.read(buf)) > 0) {
                                            out.write(buf, 0, len);
                                        }
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                                archivo.delete();
                                finish();
                                startActivity(getIntent());
                            }
                        });
                        name_setter.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                finish();
                                startActivity(getIntent());
                            }
                        });
                        name_setter.show();
                        /*
                        player = new MediaPlayer();
                        player.setOnCompletionListener(this);
                        try {
                            player.setDataSource(archivo.getAbsolutePath());
                        } catch (IOException e) {
                        }
                        try {
                            player.prepare();
                        } catch (IOException e) {
                        }
                        */

                        /*
                        final Dialog name_setter = new Dialog(context);
                        name_setter.setContentView(R.layout.set_file_name);
                        name_setter.setTitle("Seleccionar nombre");
                        */

                    }
                })
                .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            recorder.stop();
                            recorder.release();
                            archivo.delete();
                            c.setBase(SystemClock.elapsedRealtime());
                            finish();
                            startActivity(getIntent());
                        }
                    }
                })
                .setIcon(android.R.drawable.ic_dialog_alert)
                .show();

    }

}

0 个答案:

没有答案