应用持续关闭

时间:2018-07-09 21:26:10

标签: android android-mediaplayer android-mediarecorder

我正在制作一个可以录制和播放音频的应用程序,但是当我尝试运行它时,它会关闭。这是我的java:

public class MainActivity extends AppCompatActivity {
private MediaPlayer mp;
public int isPlaying = 0;
MediaRecorder recorder = new MediaRecorder();
public int isRecording = 0;

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

    ImageButton button = findViewById(R.id.pressbutton);
    button.setOnTouchListener(handleTouch);
    mp = MediaPlayer.create(this, R.raw.test);
    mp.setLooping(true);

    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    recorder.setOutputFile("R.raw.test");

}


        return true;
    }
};

public void play() {
    mp.start();
    Log.d("MediaPlayer", "started");
    isPlaying = 1;
}

public void pause() {
    mp.pause();
    Log.d("MediaPlayer", "paused");
    isPlaying = 0;
}

public void recorder(View v){
    if (isRecording == 0) {
        try {
            recorder.prepare();
            recorder.start();
            isRecording = 1;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }else if(isRecording == 1){
        recorder.stop();
        isRecording = 0;
    }
}

}

任何帮助将不胜感激。提前致谢。而且,很明显,Android Studio并没有给我任何有关错误的线索。我不得不省略一些部分,以使其适合stackoverflow。

1 个答案:

答案 0 :(得分:0)

您已确认您拥有在6.0 +上录制音频的适当权限吗?

我会将其添加到您的Android清单

<uses-permission android:name="android.permission.RECORD_AUDIO" />

,并在录制之前进行如下检查:

private void requestRecordAudioPermission() {

        String requiredPermission = Manifest.permission.RECORD_AUDIO;

        // If the user previously denied this permission then show a message explaining why
        // this permission is needed
        if (getActivity().checkCallingOrSelfPermission(requiredPermission) == PackageManager.PERMISSION_GRANTED) {

        } else {

            Toast.makeText(getActivity(), "This app needs to record audio through the microphone....", Toast.LENGTH_SHORT).show();
            requestPermissions(new String[]{requiredPermission}, 101);
        }


    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        if (requestCode == 101 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // This method is called when the  permissions are given
        }

    }