Android MediaRecorder在處理錯誤時,會拋出MediaRecorderException異常
檢查設備兼容性:確保您的設備支持MediaRecorder API。您可以使用MediaRecorder.isFeatureSupported(MediaRecorder.FEATURE_RECORD_AUDIO)
和MediaRecorder.isFeatureSupported(MediaRecorder.FEATURE_CAMERA)
等方法來檢查設備是否支持所需的特性。
檢查權限:確保您的應用具有訪問攝像頭和麥克風的權限。在AndroidManifest.xml文件中添加以下權限:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.microphone" />
并在運行時請求權限(針對Android 6.0及以上版本):
private static final int REQUEST_CODE = 1;
private void requestPermissions() {
String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO};
ActivityCompat.requestPermissions(this, permissions, REQUEST_CODE);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == REQUEST_CODE) {
boolean cameraPermission = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean audioPermission = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (cameraPermission && audioPermission) {
// Permissions granted, you can start recording
} else {
// Permissions denied, show a message to the user
}
}
}
MediaRecorder mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mediaRecorder.setOutputFile("/path/to/output/file");
try-catch
語句捕獲MediaRecorderException異常。例如:try {
mediaRecorder.prepare();
} catch (IOException e) {
e.printStackTrace();
// Handle the exception, show an error message, or clean up resources
}
if (mediaRecorder != null) {
mediaRecorder.release();
mediaRecorder = null;
}
遵循這些步驟,您可以更好地處理Android MediaRecorder中的錯誤。