При съемке видеокамеры .startCapturingVideo (null);автоматически вызывать общественность void onVideoTaken (файл видео) - PullRequest
0 голосов
/ 17 сентября 2018

Я использую следующую библиотеку для камеры и видео

https://github.com/natario1/CameraView

В то время как я снимаю видео, иногда оно отлично работает для меня. Но иногда при съемке видеокамеры .startCapturingVideo (null); автоматически вызвать публичный void onVideoTaken (файл видео).

Код активности камеры:

OnCreate ():

 setContentView(R.layout.activity_home);
        ButterKnife.bind(this);
        Fabric.with(this, new Crashlytics());
        logUser();
        view_group_photo.performClick();
        if (BuildConfig.DEBUG) {
            CameraLogger.setLogLevel(CameraLogger.LEVEL_VERBOSE);
        }
        recorder = new MediaRecorder();
        camera = findViewById(R.id.camera);
        camera.destroy();
        camera.start();
        camera.addCameraListener(new CameraListener() {
            @Override
            public void onCameraError(@NonNull CameraException exception) {
                super.onCameraError(exception);
                camera.stop();
                camera.start();
            }

            @Override
            public void onPictureTaken(byte[] jpeg) {
                super.onPictureTaken(jpeg);
                Long tsLong = System.currentTimeMillis() / 1000;
                String ts = tsLong.toString();
                try {
                    File root = new File(FILE_PATH_IMAGE);
                    if (!root.exists()) {
                        root.mkdirs();
                    }
                    @SuppressLint("SdCardPath") File myFile = new File(FILE_PATH_IMAGE + ts + FILE_EXTENSION_IMAGE);
                    myFile.createNewFile();
                    FileOutputStream stream = new FileOutputStream(myFile);
                    stream.write(jpeg);
                    stream.close();
                    Intent webViewIntent = new Intent(HomeActivity.this, ImageCropActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("file_path", FILE_PATH_IMAGE + ts + FILE_EXTENSION_IMAGE);
                    webViewIntent.putExtras(bundle);
                    webViewIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(webViewIntent);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onVideoTaken(File video) {
                super.onVideoTaken(video);
                Long tsLong = System.currentTimeMillis() / 1000;
                String ts = tsLong.toString();
                try {
                    File root = new File(FILE_PATH_VIDEO);
                    if (!root.exists()) {
                        root.mkdirs();
                    }
                    @SuppressLint("SdCardPath") File myFile = new File(FILE_PATH_VIDEO + ts + FILE_EXTENSION_VIDEO);
                    myFile.createNewFile();
                    try (InputStream in = new FileInputStream(video)) {
                        try (OutputStream out = new FileOutputStream(myFile)) {
                            // Transfer bytes from in to out
                            byte[] buf = new byte[1024];
                            int len;
                            while ((len = in.read(buf)) > 0) {
                                out.write(buf, 0, len);
                            }
                            out.close();
                        }
                    }
                    AddFileToPojo("2", FILE_TYPE_VIDEO, FILE_PATH_VIDEO + ts + FILE_EXTENSION_VIDEO);
                    IntentFunction(HomeActivity.this, ReportIncidentActivity.class);
                } catch (IOException e) {
                    Log.e("error ", "video error" + e.getMessage());
                }
            }
        });


        mGoogleApiClient = new GoogleApiClient
                .Builder(this)
                .enableAutoManage(this, 0, HomeActivity.this)
                .addApi(Places.GEO_DATA_API)
                .addApi(Places.PLACE_DETECTION_API)
                .addConnectionCallbacks(HomeActivity.this)
                .addOnConnectionFailedListener(this)
                .build();

        guessCurrentPlace();
        // get the gesture detector
        mDetector = new GestureDetector(this, new MyGestureListener());
        if (camera.getFlash() == Flash.ON) {
            imageViewFlash.setImageDrawable(getResources().getDrawable(R.drawable.flash));
        } else {
            imageViewFlash.setImageDrawable(getResources().getDrawable(R.drawable.flash_off));
        }

        viewGroupProgressLoad.setOnTouchListener(touchListener);

        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        assert connectivityManager != null;
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            ConstantVariables.INTERNET_CONNECTION = true;
            if (DEBUG) {
                Log.i("", ":: " + ConstantVariables.INTERNET_CONNECTION);
            }
        } else {
            ConstantFunctions.IntentFunction(getApplicationContext(), NoInternetActivity.class);
            ConstantVariables.INTERNET_CONNECTION = false;
            if (DEBUG) {
                Log.i("", ":: " + ConstantVariables.INTERNET_CONNECTION);
            }
        }

Запись видео с камеры fn ();

 if (camera.getSessionType() == SessionType.PICTURE) {
            camera.setSessionType(SessionType.VIDEO);
        }
        if (camera.getSessionType() != SessionType.VIDEO) {
            return;
        }
        if (mCapturingPicture || mCapturingVideo) return;
        mCapturingVideo = true;
        /*camera.setVideoMaxSize(1000000);*/
        camera.setVideoMaxDuration(300000);
        camera.startCapturingVideo(null);

остановка видео камеры fn ();

 camera.stopCapturingVideo();
 camera.destroy();
 myCountDownTimer.cancel();
 isSpeakButtonLongPressed = false;

Вход ::

I/CameraController: Restart: returned from start. Dispatching. State: STATE_STARTED
I/CameraCallbacks: dispatchOnCameraOpened com.otaliastudios.cameraview.CameraOptions@61755df
W/MediaRecorder: mediarecorder went away with unhandled events
W/MediaRecorder: mediarecorder went away with unhandled events
I/CameraController: Stop: executing. State: STATE_STARTED
Stop: about to call onStop()
I/Camera1: onStop: About to clean up.
onStop: Clean up. Ending video.
endVideoImmediately: is capturing: false
onStop: Clean up. Stopping preview.
I/Camera1: onStop: Clean up. Stopped preview.
onStop: Clean up. Releasing camera.
I/Camera1: onStop: Clean up. Released camera.
W/Camera1: onStop: Clean up. Returning.
I/CameraController: Stop: returned from onStop(). Dispatching.
I/CameraCallbacks: dispatchOnCameraClosed
E/MediaMetadataRetrieverJNI: getFrameAtTime: videoFrame is a NULL pointer
I/Choreographer: Skipped 67 frames! The application may be doing too much work on its main thread.
I/CameraPreview: crop: applied scaleX= 1.1407409
crop: applied scaleY= 1.0

1 Ответ

0 голосов
/ 02 февраля 2019

Я обновляю код,

final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                camera.startCapturingVideo(null);
            }
        }, 1000);

Я даю задержку в 1 секунду, потому что не все время startCapturingVideo инициализирует и запускает запись. В некоторых случаях оборудование не реагирует быстро. Таким образом, выполнение до следующей строки получило ошибку из-за того, что startCapturingVideo не инициировано.

...