我正在尝试开发一款相机应用程序,用户可以使用点按来录制视频以进行对焦功能,我预览相机,在预览中对焦而没有任何问题
但是当我启动录音机时,如果我尝试获取相机参数,它会给我getParameters failed (empty parameters)
异常,这是我的代码
public class CustomCameraFragmentFirstPage extends Fragment implements View.OnClickListener, SurfaceHolder.Callback, ActivityCompat.OnRequestPermissionsResultCallback, View.OnTouchListener, Camera.AutoFocusCallback {
public CustomCameraFragmentFirstPage() {
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_custom_camera_first_page, container, false);
unbinder = ButterKnife.bind(this, rootView);
resetButtons();
initiateCamera();
return rootView;
}
private void initiateCamera() {
recording = false;
recorder = new MediaRecorder();
camera = Camera.open();
initRecorder();
cameraView = (SurfaceView) rootView.findViewById(R.id.surfaceCamera);
holder = cameraView.getHolder();
holder.addCallback(this);
// holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
cameraView.setClickable(true);
cameraView.setOnClickListener(this);
// rootView.setOnTouchListener(this);
cameraView.setOnTouchListener(this);
}
@SuppressLint({"SdCardPath", "NewApi"})
private void initRecorder() {
Random rn = new Random();
int maximum = 10000000;
int minimum = 00000001;
int range = maximum - minimum + 1;
randomNum = rn.nextInt(range) + minimum + 1 - 10;
// recorder.setCamera(camera);
// recorder.setCamera(camera);focus
recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
recorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
recorder.setOrientationHint(90);//plays the video correctly
} else {
recorder.setOrientationHint(180);
}
mFileName = /* Environment.getExternalStorageDirectory().getPath()*/ "/sdcard/";
mFileName += randomNum + ".ts";
recorder.setOutputFile(mFileName);
}
private void prepareRecorder() {
recorder.setPreviewDisplay(holder.getSurface());
try {
//camera.unlock();
//recorder.setCamera(camera);
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
Toast.makeText(activity, e.getLocalizedMessage() + "", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(activity, e.getLocalizedMessage() + "", Toast.LENGTH_SHORT).show();
}
}
@OnClick(R.id.save_video)
public void startEditVideoFragment() {
startingNewFragment = true;
getFragmentManager().beginTransaction()
.replace(R.id.activity_layout_create_video, EditVideoFragment.newInstance(mFileName))
.addToBackStack(null)
.commit();
}
@OnClick(R.id.pick_gallery_button)
public void getVideoFromGallery() {
/* if (sharedPreferences.getString(Constants.SAVE_USER_ID, null) == null) {
Intent intent = new Intent(activity, ProfileActivity.class);
intent.putExtra("prompt", true);
startActivity(intent);
return;
}*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&&
ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constants.REQUEST_READ_PERMISSION);
} else {
openGallery();
}
}
private void openGallery() {
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Video"), REQUEST_TAKE_GALLERY_VIDEO);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_TAKE_GALLERY_VIDEO) {
Uri selectedImageUri = data.getData();
String selectedVideoPath = MediaSelectorUtils.getVideoFilePathFromUri(getContext(), selectedImageUri);
if (selectedVideoPath != null) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getFragmentManager().beginTransaction()
.replace(R.id.activity_layout_create_video, EditVideoFragment.newInstance(selectedVideoPath))
.addToBackStack(null)
.commit();
/*startActivity(new Intent(getActivity(), VideoEditActivity.class)
.putExtra(Constants.VIDEO_PATH, selectedVideoPath));*/
}
}
}
}
@Override
public void onResume() {
super.onResume();
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
((CreateVideoActivity) activity).toolbar.setVisibility(View.GONE);
startingNewFragment = false;
initiateCamera();
}
@Override
public void onStop() {
super.onStop();
if (!recording && !startingNewFragment) {
deleteCurrFile();
} else {
resetButtons();
recording = false;
}
}
@Override
public void onPause() {
super.onPause();
if (!recording && !startingNewFragment) {
deleteCurrFile();
} else {
resetButtons();
recording = false;
}
}
public void deleteCurrFile() {
File file = new File(mFileName);
file.delete();
}
@OnClick(R.id.back_button)
public void back() {
deleteCurrFile();
//Toast.makeText(getContext(), deleted + "", Toast.LENGTH_LONG).show();
getActivity().onBackPressed();
}
@OnClick(R.id.cancel_saved_video)
public void cancel() {
deleteCurrFile();
//Toast.makeText(getContext(), deleted + "", Toast.LENGTH_LONG).show();
getActivity().onBackPressed();
}
@OnClick(R.id.open_flash_button)
public void flipFlash() {
flashOn = !flashOn;
parameters.setFlashMode(flashOn ? Camera.Parameters.FLASH_MODE_OFF : Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
}
@OnClick(R.id.record_button)
public void record() {
try {
if (recording) {
showAcceptOrRejectButtons();
recorder.stop();
recorder.reset();
// recorder.release();
// camera.unlock();
} else {
if (!checkPermission())
requestPermission();
recordButton.setEnabled(false);
new CountDownTimer(3000, 1000) {
public void onTick(long millisUntilFinished) {
countdownTimer.setText("" + millisUntilFinished / 1000);
}
public void onFinish() {
countdownTimer.setText("");
// camera.release();
recorder.start();
recording = true;
hideButtons();
recordButton.setEnabled(true);
}
}.start();
}
} catch (Exception e) {
e.printStackTrace();
Log.d("EXC", e.getLocalizedMessage());
Toast.makeText(activity, e.getLocalizedMessage() + "", Toast.LENGTH_SHORT).show();
}
}
public void initializeCamera() {
parameters = camera.getParameters();
camera.cancelAutoFocus();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
camera.setParameters(parameters);
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(activity, e.getLocalizedMessage() + "", Toast.LENGTH_SHORT).show();
}
}
public void surfaceCreated(SurfaceHolder holder) {
initializeCamera();
prepareRecorder();
isCameraCreated = true;
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
Camera.Parameters p = camera.getParameters();
if (p.getMaxNumMeteringAreas() > 0) {
this.meteringAreaSupported = true;
}
Log.e("TAG", "surfaceChanged => w=" + width + ", h=" + height);
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
if (holder.getSurface() == null) {
// preview surface does not exist
return;
}
// stop preview before making changes
try {
camera.stopPreview();
} catch (Exception e) {
// ignore: tried to stop a non-existent preview
}
// set preview size and make any resize, rotate or reformatting changes here
// start preview with new settings
try {
Camera.Size size = getOptimalSize(parameters.getSupportedPreviewSizes(), width, height);
parameters.setPreviewSize(size.width, size.height);
camera.setParameters(p);
// camera.setDisplayOrientation(90);
camera.setPreviewDisplay(holder);
camera.startPreview();
} catch (Exception e) {
Log.d("TAG", "Error starting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
isCameraCreated = false;
try {
if (recording) {
recording = false;
}
recorder.release();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(activity, e.getLocalizedMessage() + "", Toast.LENGTH_SHORT).show();
}
}
private void requestPermission() {
requestPermissions(new
String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO, READ_EXTERNAL_STORAGE}, RequestPermissionCode);
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case RequestPermissionCode:
if (grantResults.length > 0) {
boolean StoragePermission = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
boolean RecordPermission = grantResults[1] ==
PackageManager.PERMISSION_GRANTED;
boolean ReadPermission = grantResults[2] ==
PackageManager.PERMISSION_GRANTED;
if (!(StoragePermission && RecordPermission && ReadPermission)) {
Toast.makeText(getActivity(), "Permission Denied " + StoragePermission + " " + RecordPermission, Toast.LENGTH_LONG).show();
}
}
break;
}
}
public boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(getContext(),
WRITE_EXTERNAL_STORAGE);
int result1 = ContextCompat.checkSelfPermission(getContext(),
RECORD_AUDIO);
return result == PackageManager.PERMISSION_GRANTED &&
result1 == PackageManager.PERMISSION_GRANTED;
}
@Override
public void onClick(View view) {
}
@Override
public boolean onTouch(View view, final MotionEvent motionEvent) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
focusOnTouch(motionEvent);
}
}, 200);
//}
Log.d("TOUCH", "HAPPENED");
return true;
}
@Override
public void onAutoFocus(boolean b, Camera camera) {
// camera.cancelAutoFocus();
Camera.Parameters params = camera.getParameters();
if (params.getFocusMode() != Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE) {
params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
camera.setParameters(params);
}
}
private Rect calculateTapArea(float x, float y, float coefficient) {
int left = clamp(Float.valueOf((x / cameraView.getWidth()) * 2000 - 1000).intValue(), FOCUS_AREA_SIZE);
int top = clamp(Float.valueOf((y / cameraView.getHeight()) * 2000 - 1000).intValue(), FOCUS_AREA_SIZE);
return new Rect(left, top, left + FOCUS_AREA_SIZE, top + FOCUS_AREA_SIZE);
}
private int clamp(int touchCoordinateInCameraReper, int focusAreaSize) {
int result;
if (Math.abs(touchCoordinateInCameraReper) + focusAreaSize / 2 > 1000) {
if (touchCoordinateInCameraReper > 0) {
result = 1000 - focusAreaSize / 2;
} else {
result = -1000 + focusAreaSize / 2;
}
} else {
result = touchCoordinateInCameraReper - focusAreaSize / 2;
}
return result;
}
protected void focusOnTouch(MotionEvent event) {
if (camera != null) {
Rect focusRect = calculateTapArea(event.getX(), event.getY(), 1f);
Rect meteringRect = calculateTapArea(event.getX(), event.getY(), 1.5f);
// camera.lock();
Camera.Parameters parameters = camera.getParameters();
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
if (parameters.getMaxNumFocusAreas() > 0) {
List<Camera.Area> mylist = new ArrayList<Camera.Area>();
mylist.add(new Camera.Area(focusRect, 1000));
parameters.setFocusAreas(mylist);
if (meteringAreaSupported) {
parameters.setMeteringAreas(mylist);
}
}
// camera.unlock();
camera.setParameters(parameters);
camera.autoFocus(this);
}
}
private Camera.Size getOptimalSize(List<Camera.Size> sizes, int w, int h) {
final double ASPECT_TOLERANCE = 0.2;
double targetRatio = (double) w / h;
if (sizes == null)
return null;
Camera.Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
int targetHeight = h;
// Try to find an size match aspect ratio and size
for (Camera.Size size : sizes) {
// Log.d("CameraActivity", "Checking size " + size.width + "w " + size.height + "h");
double ratio = (double) size.width / size.height;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE)
continue;
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
// Cannot find the one match the aspect ratio, ignore the requirement
if (optimalSize == null) {
minDiff = Double.MAX_VALUE;
for (Camera.Size size : sizes) {
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
}
// Log.d("CameraActivity", "Using size: " + optimalSize.width + "w " + optimalSize.height + "h");
return optimalSize;
}
}
答案 0 :(得分:0)
问题是我在创建曲面之前初始化了录音机,所以我所做的就是从初始化相机中移除MKUserLocation
函数调用并将其调用为initRecorder()