尝试在空对象引用上调用虚拟方法 'void android.media.MediaRecorder.prepare()'

Attempt to invoke virtual method 'void android.media.MediaRecorder.prepare()' on a null object reference

我对android只有基本的了解。今天我开发了一个录音应用程序,但问题是用户可以录制音频,停止录音,它可以播放音频,但是当用户再次按下录音按钮播放后,应用程序崩溃了,谁能帮我?

这是我的主要activity

package com.hackerinside.jaisonjoseph.sample_recorder;

   import android.media.MediaPlayer;
   import android.media.MediaRecorder;
   import android.os.Bundle;
   import android.os.Environment;
   import android.provider.MediaStore;
   import android.support.design.widget.FloatingActionButton;
   import android.support.design.widget.Snackbar;
   import android.support.v7.app.AppCompatActivity;
   import android.support.v7.widget.Toolbar;
   import android.view.View;
   import android.view.Menu;
   import android.view.MenuItem;
   import android.widget.Button;
   import android.widget.Toast;

    import java.io.IOException;

public class MainActivity extends AppCompatActivity {

private Button play,stop,record;
private MediaRecorder myAudioRecorder;
private String outputfile;


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

    play=(Button)findViewById(R.id.play);
    stop=(Button)findViewById(R.id.stop);
    record=(Button)findViewById(R.id.record);
    stop.setEnabled(false);
    play.setEnabled(false);


  outputfile= Environment.getExternalStorageDirectory().getAbsolutePath()+"/recording_"+System.currentTimeMillis()+".mp3";



    myAudioRecorder=new MediaRecorder();
    myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
    myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.DEFAULT);
    myAudioRecorder.setOutputFile(outputfile);

 record.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View view) {

         try {

             myAudioRecorder.prepare();
             myAudioRecorder.start();
     }
     catch (IllegalStateException ise){



     }catch (IOException ioe){



         }
            record.setEnabled(false);
            stop.setEnabled(true);
            Toast.makeText(getApplicationContext(),"record startded",Toast.LENGTH_LONG).show();

     }

 });





    stop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {



            myAudioRecorder.stop();
            record.setEnabled(true);
            myAudioRecorder.release();
            myAudioRecorder=null;
            stop.setEnabled(false);
            play.setEnabled(true);
            Toast.makeText(getApplicationContext(),"recorded audio",Toast.LENGTH_LONG).show();

        }

    });
            play.setOnClickListener(new View.OnClickListener() {
                 @Override
                public void onClick(View view) {
                     MediaPlayer mediaPlayer=new MediaPlayer();

                     try {
                             mediaPlayer.setDataSource(outputfile);
                             mediaPlayer.prepare();
                             mediaPlayer.start();
                             Toast.makeText(getApplicationContext(),"playing  audio",Toast.LENGTH_LONG).show();
    }
    catch (Exception e)
    {
 // here
    }

}
   });








    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;











}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

如果你查看 documentations 它说你在释放它后无法访问记录器,这就是你在按下停止时正在做的事情,你必须实例化新的记录器或者根本不放开它。

尝试添加这个

myAudioRecorder=new MediaRecorder();

在你的

record.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View view) {

     try { 
         myAudioRecorder=new MediaRecorder();
         myAudioRecorder.prepare();
         myAudioRecorder.start();
 }

或者您可以从停止按钮点击中删除 myAudioRecorder.release();

它应该在 onPause() 期间在您的 activity

上发布

那是因为,你在停止的时候设置了nullmediaRecorder

stop.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        myAudioRecorder.stop();
        record.setEnabled(true);
        myAudioRecorder.release();
        myAudioRecorder=null;
        stop.setEnabled(false);
        play.setEnabled(true);
        Toast.makeText(getApplicationContext(),"recorded audio",Toast.LENGTH_LONG).show();
    }

});

当您再次点击记录时,这将被执行,

    record.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View view) {

         try {
             // myAudioRecorder is null when you come up second time.
             // Initialize myAudioRecorder to prevent an exception.
             myAudioRecorder.prepare();
             myAudioRecorder.start();
         } catch (IllegalStateException ise){

         } catch (IOException ioe) {

         }
         record.setEnabled(false);
         stop.setEnabled(true);
         Toast.makeText(getApplicationContext(),"record startded",Toast.LENGTH_LONG).show();
     }
 });

myAudioRecorder.prepare(); 将通过 NullPointerException,因为 myAudioRecordernull
虽然上面的代码在try.. catch但是你没抓到NullPointerException,App会崩溃