Media Recorder无法启动

时间:2018-09-06 18:25:37

标签: java android logcat

我一直在尝试使用Mediarecorder,但是它根本无法启动,这给了我下面给出的错误,当我将记录器放进去时,尝试去抓住记录器。停止不起作用,给了我类似的提示错误,尽管我在Manifest.xml中为Recording.Audio和Write_External_Storage写了权限代码。

public class Recording extends AppCompatActivity {

private MediaRecorder recorder;
private MediaPlayer myPlayer;
private String OUTPUTFILE;
private TextView myCount;
private Button Play;
private Button Next;
private TextView myQuestion;
private int value;


@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    switch (requestCode){
        case 1:{
            if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                // do something


            }

            else {
                Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
            }
            return;
        }
    }
}

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

    OUTPUTFILE =
            new File(
                    Environment.getExternalStoragePublicDirectory(
                            Environment.DIRECTORY_DCIM),
                    "audiorecorder.3gp")
                    .getAbsolutePath();
    myCount  = (TextView) findViewById(R.id.myCount);
    Play = (Button) findViewById(R.id.Play);
    Next = (Button) findViewById(R.id.Next);
    myQuestion = (TextView) findViewById(R.id.myQuestion);


    //recorder.start();





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

        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO)) {
            Toast.makeText(this, "Please grand permission to record audio", Toast.LENGTH_SHORT).show();

            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 1);
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 1);
        }
    }

    else {

        value = MainActivity.GenerateValue();
        myQuestion.setText(MainActivity.mylist.get(value) + " ./?");
        Play.setEnabled(false);
        Next.setEnabled(false);

        fiveSeconds();

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

                if(Play.getId() == R.id.Play){
                    playBack();
                    Play.setBackground(getResources().getDrawable(R.drawable.pause));
                }

                else {
                    stopPlayBack();
                    Play.setBackground(getResources().getDrawable(R.drawable.play));
                }

            }
        });

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

                Intent theIntent = new Intent(getApplicationContext(), Make_Notes.class);
                startActivity(theIntent);
            }
        });



    }


}

private void fiveSeconds() {

    new CountDownTimer(5000, 1000) {

        public void onTick(long milliseconds) {

            //  Log.i("Seconds Left", String.valueOf(milliseconds/1000));
            myCount.setText(String.valueOf(milliseconds / 1000));
            if (milliseconds / 1000 < 4) {
                myCount.setTextColor(Color.RED);
            }

        }

        public void onFinish() {
            sixtySeconds();





           recorder = new MediaRecorder();
            //recorder.reset();
            recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            recorder.setOutputFile(OUTPUTFILE);
           try {

               recorder.prepare();

            } catch (IOException e) {
                e.printStackTrace();
            }

            recorder.start();


            Toast.makeText(Recording.this, "Start!", Toast.LENGTH_SHORT).show();

        }
    }.start();
}

private void sixtySeconds() {
    CountDownTimer start = new CountDownTimer(3000, 1000) {

        public void onTick(long milliseconds) {

            // Log.i("Seconds Left", String.valueOf(milliseconds/1000));
            myCount.setText(String.valueOf(milliseconds / 1000));
            if (milliseconds / 1000 < 4) {
                myCount.setTextColor(Color.RED);
            }

        }

        public void onFinish() {

                recorder.stop();



            Play.setEnabled(true);
            Next.setEnabled(true);

        }
    }.start();


}

private void stopRecording(){
    if(recorder != null){
        recorder.stop();

    }
    else {
        Toast.makeText(this, "There is no recorder to play", Toast.LENGTH_SHORT).show();
    }

}

private void playBack(){

    myPlayer = new MediaPlayer();
    try {
        myPlayer.setDataSource(OUTPUTFILE);
        myPlayer.prepare();
    } catch (IOException e) {
        e.printStackTrace();
    }
    myPlayer.start();


}

private void stopPlayBack(){
     myPlayer.stop();

        Toast.makeText(this, "There is no media to stop", Toast.LENGTH_SHORT).show();



}

}

Logcat错误为:

09-15 15:48:59.183 20615-20615/com.example.abdullah.be_fluent 
E/MediaRecorder: start called in an invalid state: 4
09-15 15:48:59.192 20615-20615/com.example.abdullah.be_fluent 
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.abdullah.be_fluent, PID: 20615
java.lang.IllegalStateException
    at android.media.MediaRecorder._start(Native Method)
    at android.media.MediaRecorder.start(MediaRecorder.java:1309)
    at com.example.abdullah.be_fluent.Recording$3.onFinish(Recording.java:145) // the Recording.java: 145 is in blue which is myrecorder.start//
    at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:127)
    at android.os.Handler.dispatchMessage(Handler.java:105)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6944)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)

1 个答案:

答案 0 :(得分:0)

仅在授予权限的情况下尝试设置MediaRecorder,这样重构代码:

 @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {
            case 1: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // do something
                    setupMediaRecorder();
                    fiveSeconds();

                } else {
                    Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
                }
                return;
            }
        }
    }

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

        OUTPUTFILE = Environment.getExternalStorageDirectory() + "/audiorecorder.m4a";
        myCount = (TextView) findViewById(R.id.myCount);
        Play = (Button) findViewById(R.id.Play);
        Next = (Button) findViewById(R.id.Next);
        myQuestion = (TextView) findViewById(R.id.myQuestion);



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

            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO)) {
                Toast.makeText(this, "Please grand permission to record audio", Toast.LENGTH_SHORT).show();

                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 1);
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 1);
            }
        } else {

            myQuestion.setText("MainActivity.mylist.get(value) +  ./?");
            Play.setEnabled(false);
            Next.setEnabled(false);

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

                    if (Play.getId() == R.id.Play) {
                        playBack();
                    } else {
                        stopPlayBack();
                    }

                }
            });

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

                    Intent theIntent = new Intent(getApplicationContext(), MainActivity.class);
                    startActivity(theIntent);
                }
            });
            setupMediaRecorder();
            fiveSeconds();

        }


    }

    private void setupMediaRecorder() {
        recorder = new MediaRecorder();
        recorder.reset();
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        recorder.setOutputFile(OUTPUTFILE);
        try {
            recorder.prepare();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }