Syord

CameraFragment_Ap21

Jan 17th, 2019
181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 63.16 KB | None | 0 0
  1. package com.three_embed.com.starmenew.Fragment_Manager.PostNewFragments;
  2.  
  3. import android.Manifest;
  4. import android.animation.Animator;
  5. import android.animation.AnimatorListenerAdapter;
  6. import android.animation.AnimatorSet;
  7. import android.animation.ObjectAnimator;
  8. import android.annotation.SuppressLint;
  9. import android.app.Activity;
  10. import android.content.Context;
  11. import android.content.Intent;
  12. import android.content.pm.PackageManager;
  13. import android.content.res.Configuration;
  14. import android.graphics.ImageFormat;
  15. import android.graphics.Matrix;
  16. import android.graphics.Point;
  17. import android.graphics.RectF;
  18. import android.graphics.SurfaceTexture;
  19. import android.hardware.camera2.CameraAccessException;
  20. import android.hardware.camera2.CameraCaptureSession;
  21. import android.hardware.camera2.CameraCharacteristics;
  22. import android.hardware.camera2.CameraDevice;
  23. import android.hardware.camera2.CameraManager;
  24. import android.hardware.camera2.CameraMetadata;
  25. import android.hardware.camera2.CaptureRequest;
  26. import android.hardware.camera2.CaptureResult;
  27. import android.hardware.camera2.TotalCaptureResult;
  28. import android.hardware.camera2.params.StreamConfigurationMap;
  29. import android.media.Image;
  30. import android.media.ImageReader;
  31. import android.media.MediaRecorder;
  32. import android.net.Uri;
  33. import android.os.Build;
  34. import android.os.Bundle;
  35. import android.os.Handler;
  36. import android.os.HandlerThread;
  37. import android.provider.Settings;
  38. import android.support.annotation.NonNull;
  39. import android.support.annotation.RequiresApi;
  40. import android.support.v4.app.Fragment;
  41. import android.support.v4.content.ContextCompat;
  42. import android.support.v4.view.ViewPager;
  43. import android.util.Size;
  44. import android.util.SparseIntArray;
  45. import android.view.LayoutInflater;
  46. import android.view.Surface;
  47. import android.view.TextureView;
  48. import android.view.View;
  49. import android.view.ViewGroup;
  50. import android.view.animation.AccelerateInterpolator;
  51. import android.view.animation.Animation;
  52. import android.view.animation.AnimationUtils;
  53. import android.view.animation.DecelerateInterpolator;
  54. import android.view.animation.Interpolator;
  55. import android.widget.Button;
  56. import android.widget.ImageView;
  57. import android.widget.ProgressBar;
  58. import android.widget.RelativeLayout;
  59. import android.widget.TextView;
  60. import android.widget.Toast;
  61.  
  62. import com.three_embed.com.starmenew.Activity_Manager.PostNewActivity;
  63. import com.three_embed.com.starmenew.Adpater_classes.Post_view_fake_pager_adp;
  64. import com.three_embed.com.starmenew.Camera_handler.AutoFitTextureView;
  65. import com.three_embed.com.starmenew.CommonClasses.Utility;
  66. import com.three_embed.com.starmenew.Coustom_scroll_view.Fake_pager_scroll_view;
  67. import com.three_embed.com.starmenew.Interface_Manager.Camera_Flash;
  68. import com.three_embed.com.starmenew.Permission_Ap23.App_permission_23;
  69. import com.three_embed.com.starmenew.R;
  70. import com.three_embed.com.starmenew.Songplayer.UAudioRecorder.AudioRecordingHandler;
  71. import com.three_embed.com.starmenew.Songplayer.UAudioRecorder.UAudioRecorder;
  72. import com.three_embed.com.starmenew.Songplayer.MovieCreator.UMediaRecorder;
  73. import com.videocompressor.com.File_merger;
  74.  
  75. import java.io.File;
  76. import java.io.FileOutputStream;
  77. import java.io.IOException;
  78. import java.nio.ByteBuffer;
  79. import java.util.ArrayList;
  80. import java.util.Arrays;
  81. import java.util.Collections;
  82. import java.util.Comparator;
  83. import java.util.List;
  84. import java.util.Locale;
  85. import java.util.Timer;
  86. import java.util.TimerTask;
  87. import java.util.concurrent.Semaphore;
  88. import java.util.concurrent.TimeUnit;
  89.  
  90. /**
  91.  * <h2>CameraFragment_Ap21</h2>
  92.  * A simple {@link Fragment} subclass.
  93.  * Use the {@link CameraFragment_Ap21#newInstance} factory method to
  94.  * create an instance of this fragment.
  95.  */
  96. @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
  97. public class CameraFragment_Ap21 extends Fragment implements View.OnClickListener,App_permission_23.Permission_Callback
  98. {
  99.     private PostNewActivity postNewActivity;
  100.     private Activity parentactivity;
  101.     File tempVideo;
  102.  
  103.     private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
  104.     private static final SparseIntArray DEFAULT_ORIENTATIONS = new SparseIntArray();
  105.     private static final SparseIntArray INVERSE_ORIENTATIONS = new SparseIntArray();
  106.     private static final int SENSOR_ORIENTATION_DEFAULT_DEGREES = 90;
  107.     private static final int SENSOR_ORIENTATION_INVERSE_DEGREES = 270;
  108.     static
  109.     {
  110.         ORIENTATIONS.append(Surface.ROTATION_0, 90);
  111.         ORIENTATIONS.append(Surface.ROTATION_90, 0);
  112.         ORIENTATIONS.append(Surface.ROTATION_180, 270);
  113.         ORIENTATIONS.append(Surface.ROTATION_270, 180);
  114.     }
  115.     static
  116.     {
  117.         DEFAULT_ORIENTATIONS.append(Surface.ROTATION_0, 90);
  118.         DEFAULT_ORIENTATIONS.append(Surface.ROTATION_90, 0);
  119.         DEFAULT_ORIENTATIONS.append(Surface.ROTATION_180, 270);
  120.         DEFAULT_ORIENTATIONS.append(Surface.ROTATION_270, 180);
  121.     }
  122.     static
  123.     {
  124.         INVERSE_ORIENTATIONS.append(Surface.ROTATION_0, 270);
  125.         INVERSE_ORIENTATIONS.append(Surface.ROTATION_90, 180);
  126.         INVERSE_ORIENTATIONS.append(Surface.ROTATION_180, 90);
  127.         INVERSE_ORIENTATIONS.append(Surface.ROTATION_270, 0);
  128.     }
  129.  
  130.  
  131.     private static final int STATE_PREVIEW = 0;
  132.     private static final int STATE_WAITING_LOCK = 1;
  133.     private static final int STATE_WAITING_PRECAPTURE = 2;
  134.     private static final int STATE_WAITING_NON_PRECAPTURE = 3;
  135.     private static final int STATE_PICTURE_TAKEN = 4;
  136.     private static final int MAX_PREVIEW_WIDTH = 2960;
  137.     private static final int MAX_PREVIEW_HEIGHT = 1440;
  138.     private String mNextVideoAbsolutePath;
  139.     private ProgressBar record_progressBar;
  140.     private TextView recorded_time;
  141.     public String CAMERA_TAG="Camera_permission";
  142.     public String RECORDER_TAG="Recorder_permission";
  143.     private View mShutter;
  144.     private RelativeLayout main_Camera_container,premission_denined,bottom_layout;
  145.     private App_permission_23 app_permission_23;
  146.     private static final Interpolator ACCELERATE_INTERPOLATOR = new AccelerateInterpolator();
  147.     private static final Interpolator DECELERATE_INTERPOLATOR = new DecelerateInterpolator();
  148.     private boolean isTurn_button_click=false;
  149.     private Fake_pager_scroll_view fake_pager;
  150.     private boolean isVideo_active=false;
  151.     private String mCameraId= Camera_Flash.FACING_FRONT;
  152.     private AutoFitTextureView mTextureView;
  153.     private CameraCaptureSession mCaptureSession;
  154.     private CameraDevice mCameraDevice;
  155.     private Size mPreviewSize;
  156.     private Size mVideoSize;
  157.     private UMediaRecorder mMediaRecorder;
  158.     private boolean mIsRecordingVideo;
  159.     private HandlerThread mBackgroundThread;
  160.     private Handler mBackgroundHandler;
  161.     private ImageReader mImageReader;
  162.     private int previous_recorded_time=0;
  163.     private Timer timer;
  164.     private ArrayList<String> record_file_paths;
  165.     private boolean isRecord_file_exist=false;
  166.     TextView userScoreTextView;
  167.     private AudioRecordingHandler arh;
  168.  
  169.     private CameraFragmentActionListener listener;
  170.     UAudioRecorder audioRecorder;
  171.     /**
  172.      * This a callback object for the {@link ImageReader}.
  173.      * "onImageAvailable" will be called when a
  174.      * still image is ready to be saved.
  175.      */
  176.     private boolean isForCapture=false;
  177.     private final ImageReader.OnImageAvailableListener mOnImageAvailableListener = new ImageReader.OnImageAvailableListener() {
  178.         @Override
  179.         public void onImageAvailable(ImageReader reader)
  180.         {
  181.             if(!isForCapture) {
  182.                 isForCapture=true;
  183.                 mBackgroundHandler.post(new ImageSaver(reader.acquireNextImage()));
  184.             }
  185.         }
  186.     };
  187.     private CaptureRequest.Builder mPreviewRequestBuilder;
  188.     private CaptureRequest mPreviewRequest;
  189.     private int mState = STATE_PREVIEW;
  190.     private Semaphore mCameraOpenCloseLock = new Semaphore(1);
  191.     private boolean mFlashSupported;
  192.     private int mSensorOrientation;
  193.     private ImageView take_photo;
  194.     private CameraManager manager;
  195.     File finalOutFile;
  196.     File aacfile;
  197.  
  198.     /**
  199.      * Shows a {@link Toast} on the UI thread.
  200.      * @param text The message to show
  201.      */
  202.     private void showToast(final String text)
  203.     {
  204.         if (parentactivity!= null)
  205.         {
  206.             parentactivity.runOnUiThread(new Runnable() {
  207.                 @Override
  208.                 public void run() {
  209.                     Toast.makeText(parentactivity, text, Toast.LENGTH_SHORT).show();
  210.                 }
  211.             });
  212.         }
  213.     }
  214.     public CameraFragment_Ap21()
  215.     {}
  216.  
  217.     /**
  218.      * Use this factory method to create a new instance of
  219.      * this fragment using the provided parameters.
  220.      * @param param1 Parameter 1.
  221.      * @param param2 Parameter 2.
  222.      * @return A new instance of fragment CameraFragment_Ap21.
  223.      */
  224.     public static CameraFragment_Ap21 newInstance(String param1, String param2)
  225.     {
  226.         return new CameraFragment_Ap21();
  227.     }
  228.  
  229.     @Override
  230.     public void onCreate(Bundle savedInstanceState)
  231.     {
  232.         super.onCreate(savedInstanceState);
  233.         parentactivity = getActivity();
  234.         record_file_paths = new ArrayList<>();
  235.         postNewActivity = (PostNewActivity) parentactivity;
  236.         app_permission_23= App_permission_23.getInstance();
  237.         manager = (CameraManager)parentactivity.getSystemService(Context.CAMERA_SERVICE);
  238.     }
  239.  
  240.     @Override
  241.     public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
  242.         View view=inflater.inflate(R.layout.fragment_camera_fragment__ap21, container, false);
  243.         init_xml_content(view);
  244.         return view;
  245.     }
  246.  
  247.     private void init_xml_content(View view)
  248.     {
  249.         fake_pager= view.findViewById(R.id.fake_pager);
  250.         handel_Fake_pager();
  251.         //main_Camera_container= view.findViewById(R.id.main_Camera_container);
  252.         premission_denined= view.findViewById(R.id.premission_denined);
  253.         //bottom_layout= view.findViewById(R.id.bottom_layout);
  254.         mTextureView = view.findViewById(R.id.mCameraPhotoView);
  255.         record_progressBar= view.findViewById(R.id.record_progressBar);
  256.         take_photo = view.findViewById(R.id.take_photo);
  257.         take_photo.setOnClickListener(this);
  258.         mShutter=view.findViewById(R.id.mShutter);
  259.         Button turn_on_button = view.findViewById(R.id.turn_on_button);
  260.         turn_on_button.setOnClickListener(this);
  261.         TextView sub_title = view.findViewById(R.id.sub_title);
  262.         sub_title.setTypeface(postNewActivity.RobotoRegular);
  263.         TextView top_title = view.findViewById(R.id.top_title);
  264.         top_title.setTypeface(postNewActivity.RobotoBold);
  265.         recorded_time = view.findViewById(R.id.recorded_time);
  266.         recorded_time.setTypeface(postNewActivity.RobotoRegular);
  267.         userScoreTextView = view.findViewById(R.id.user_score_text);
  268.         audioRecorder = new UAudioRecorder(getContext());
  269.     }
  270.     /**
  271.      * {@link TextureView.SurfaceTextureListener} handles several lifecycle events on a
  272.      * {@link TextureView}.
  273.      */
  274.     private final TextureView.SurfaceTextureListener mSurfaceTextureListener = new TextureView.SurfaceTextureListener()
  275.     {
  276.  
  277.         @Override
  278.         public void onSurfaceTextureAvailable(SurfaceTexture texture, int width, int height)
  279.         {
  280.             openCamera(width, height);
  281.         }
  282.         @Override
  283.         public void onSurfaceTextureSizeChanged(SurfaceTexture texture, int width, int height)
  284.         {
  285.             configureTransform(width, height);
  286.         }
  287.         @Override
  288.         public boolean onSurfaceTextureDestroyed(SurfaceTexture texture)
  289.         {
  290.             return true;
  291.         }
  292.         @Override
  293.         public void onSurfaceTextureUpdated(SurfaceTexture texture)
  294.         {}
  295.     };
  296.  
  297.     private CameraCaptureSession.CaptureCallback mCaptureCallback=new CameraCaptureSession.CaptureCallback()
  298.     {
  299.  
  300.  
  301.         private void process(CaptureResult result)
  302.         {
  303.  
  304.             switch (mState) {
  305.                 case STATE_PREVIEW: {
  306.                     break;
  307.                 }
  308.                 case STATE_WAITING_LOCK: {
  309.                     Integer afState = result.get(CaptureResult.CONTROL_AF_STATE);
  310.                     if (afState == null) {
  311.                         captureStillPicture();
  312.                     } else if (CaptureResult.CONTROL_AF_STATE_FOCUSED_LOCKED == afState ||
  313.                             CaptureResult.CONTROL_AF_STATE_NOT_FOCUSED_LOCKED == afState)
  314.                     {
  315.                         Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
  316.                         if (aeState == null ||
  317.                                 aeState == CaptureResult.CONTROL_AE_STATE_CONVERGED) {
  318.                             mState = STATE_PICTURE_TAKEN;
  319.                             captureStillPicture();
  320.                         } else {
  321.                             runPrecaptureSequence();
  322.                         }
  323.                     }
  324.                     break;
  325.                 }
  326.                 case STATE_WAITING_PRECAPTURE:
  327.                 {
  328.                     Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
  329.                     if (aeState == null ||
  330.                             aeState == CaptureResult.CONTROL_AE_STATE_PRECAPTURE ||
  331.                             aeState == CaptureRequest.CONTROL_AE_STATE_FLASH_REQUIRED) {
  332.                         mState = STATE_WAITING_NON_PRECAPTURE;
  333.                     }
  334.                     break;
  335.                 }
  336.                 case STATE_WAITING_NON_PRECAPTURE:
  337.                 {
  338.                     Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
  339.                     if (aeState == null || aeState != CaptureResult.CONTROL_AE_STATE_PRECAPTURE) {
  340.                         mState = STATE_PICTURE_TAKEN;
  341.                         captureStillPicture();
  342.                     }
  343.                     break;
  344.                 }
  345.             }
  346.         }
  347.         @Override
  348.         public void onCaptureProgressed(@NonNull CameraCaptureSession session,
  349.                                         @NonNull CaptureRequest request,
  350.                                         @NonNull CaptureResult partialResult) {
  351.             process(partialResult);
  352.         }
  353.  
  354.         @Override
  355.         public void onCaptureCompleted(@NonNull CameraCaptureSession session,
  356.                                        @NonNull CaptureRequest request,
  357.                                        @NonNull TotalCaptureResult result)
  358.         {
  359.             process(result);
  360.         }
  361.     };
  362.  
  363.     private final CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback()
  364.     {
  365.         @Override
  366.         public void onOpened(@NonNull CameraDevice cameraDevice)
  367.         {
  368.             mCameraOpenCloseLock.release();
  369.             mCameraDevice = cameraDevice;
  370.             createCameraPreviewSession();
  371.         }
  372.         @Override
  373.         public void onDisconnected(@NonNull CameraDevice cameraDevice)
  374.         {
  375.             mCameraOpenCloseLock.release();
  376.             cameraDevice.close();
  377.             mCameraDevice = null;
  378.         }
  379.         @Override
  380.         public void onError(@NonNull CameraDevice cameraDevice, int error)
  381.         {
  382.             mCameraOpenCloseLock.release();
  383.             cameraDevice.close();
  384.             mCameraDevice = null;
  385.             if (null != parentactivity)
  386.             {
  387.                 parentactivity.finish();
  388.             }
  389.         }
  390.     };
  391.  
  392.  
  393.     /**
  394.      * Given {@code choices} of {@code Size}s supported by a camera, choose the smallest one that
  395.      * is at least as large as the respective texture view size, and that is at most as large as the
  396.      * respective max size, and whose aspect ratio matches with the specified value. If such size
  397.      * doesn't exist, choose the largest one that is at most as large as the respective max size,
  398.      * and whose aspect ratio matches with the specified value.
  399.      *
  400.      * @param choices           The list of sizes that the camera supports for the intended output
  401.      *                          class
  402.      * @param textureViewWidth  The width of the texture view relative to sensor coordinate
  403.      * @param textureViewHeight The height of the texture view relative to sensor coordinate
  404.      * @param maxWidth          The maximum width that can be chosen
  405.      * @param maxHeight         The maximum height that can be chosen
  406.      * @param aspectRatio       The aspect ratio
  407.      * @return The optimal {@code Size}, or an arbitrary one if none were big enough
  408.      */
  409.     private static Size chooseOptimalSize(Size[] choices, int textureViewWidth, int textureViewHeight, int maxWidth, int maxHeight, Size aspectRatio)
  410.     {
  411.         List<Size> bigEnough = new ArrayList<>();
  412.         List<Size> notBigEnough = new ArrayList<>();
  413.         int w = aspectRatio.getWidth();
  414.         int h = aspectRatio.getHeight();
  415.         for (Size option : choices) {
  416.             if (option.getWidth() <= maxWidth && option.getHeight() <= maxHeight &&
  417.                     option.getHeight() == option.getWidth() * h / w) {
  418.                 if (option.getWidth() >= textureViewWidth &&
  419.                         option.getHeight() >= textureViewHeight) {
  420.                     bigEnough.add(option);
  421.                 } else {
  422.                     notBigEnough.add(option);
  423.                 }
  424.             }
  425.         }
  426.         if (bigEnough.size() > 0)
  427.         {
  428.             return Collections.min(bigEnough, new CompareSizesByArea());
  429.         } else if (notBigEnough.size() > 0)
  430.         {
  431.             return Collections.max(notBigEnough, new CompareSizesByArea());
  432.         } else
  433.         {
  434.             return choices[0];
  435.         }
  436.     }
  437.  
  438.     /**
  439.      * Given {@code choices} of {@code Size}s supported by a camera, chooses the smallest one whose
  440.      * width and height are at least as large as the respective requested values, and whose aspect
  441.      * ratio matches with the specified value.
  442.      *
  443.      * @param choices     The list of sizes that the camera supports for the intended output class
  444.      * @param width       The minimum desired width
  445.      * @param height      The minimum desired height
  446.      * @param aspectRatio The aspect ratio
  447.      * @return The optimal {@code Size}, or an arbitrary one if none were big enough
  448.      */
  449.     private static Size chooseOptimalSize(Size[] choices, int width, int height, Size aspectRatio) {
  450.         List<Size> bigEnough = new ArrayList<>();
  451.         int w = aspectRatio.getWidth();
  452.         int h = aspectRatio.getHeight();
  453.         for (Size option : choices) {
  454.             if (option.getHeight() == option.getWidth() * h / w &&
  455.                     option.getWidth() >= width && option.getHeight() >= height) {
  456.                 bigEnough.add(option);
  457.             }
  458.         }
  459.         if (bigEnough.size() > 0) {
  460.             return Collections.min(bigEnough, new CompareSizesByArea());
  461.         } else {
  462.             return choices[0];
  463.         }
  464.     }
  465.  
  466.     @Override
  467.     public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
  468.     {
  469.         app_permission_23.onRequestPermissionsResult(requestCode,permissions,grantResults);
  470.     }
  471.  
  472.     @Override
  473.     public void onResume()
  474.     {
  475.         super.onResume();
  476.         if (postNewActivity.isCameraPermissionGranted) {
  477.             startBackgroundThread();
  478.             if (mTextureView.isAvailable()) {
  479.                 openCamera(mTextureView.getWidth(), mTextureView.getHeight());
  480.             } else {
  481.                 mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
  482.             }
  483.         } else {
  484.             permission_layout_handeler(false);
  485.         }
  486.     }
  487.  
  488.     @Override
  489.     public void onPause()
  490.     {
  491.         if (timer != null)
  492.         {
  493.             timer.cancel();
  494.         }
  495.         stopRecordingVideo();
  496.         closeCamera();
  497.         stopBackgroundThread();
  498.         super.onPause();
  499.     }
  500.  
  501.  
  502.     @Override
  503.     public void onStop()
  504.     {
  505.         if (timer != null) {
  506.             timer.cancel();
  507.         }
  508.  
  509.         stopRecordingVideo();
  510.         closeCamera();
  511.         stopBackgroundThread();
  512.         super.onStop();
  513.     }
  514.  
  515.     @Override
  516.     public void onDestroy()
  517.     {
  518.         if (timer != null) {
  519.             timer.cancel();
  520.         }
  521.         stopRecordingVideo();
  522.         closeCamera();
  523.         stopBackgroundThread();
  524.         super.onDestroy();
  525.     }
  526.  
  527.  
  528.     @Override
  529.     public void onDetach() {
  530.         if (timer != null) {
  531.             timer.cancel();
  532.         }
  533.         super.onDetach();
  534.     }
  535.    
  536.     public void  handel_button_Selected(boolean isSelected) {
  537.         //take_photo.setSelected(isSelected);
  538.     }
  539.     public void handel_Video_view(boolean isAcive) {
  540.  
  541.         if(isAcive) {
  542.             record_progressBar.setVisibility(View.VISIBLE);
  543.         } else {
  544.             record_progressBar.setVisibility(View.INVISIBLE);
  545.             recorded_time.setVisibility(View.INVISIBLE);
  546.         }
  547.     }
  548.  
  549.     /**
  550.      * <h2>permission_visibality</h2>
  551.      * <P>
  552.      *   Handel all the layout visibality.
  553.      * </P>
  554.      * @param isPermission_granted contains flag that tell permission is granted or not.
  555.      * */
  556.     private void permission_layout_handeler(boolean isPermission_granted)
  557.     {
  558.         if(isPermission_granted)
  559.         {
  560.             postNewActivity.isCameraPermissionGranted =true;
  561.             //main_Camera_container.setVisibility(View.VISIBLE);
  562.             //bottom_layout.setVisibility(View.VISIBLE);
  563.             premission_denined.setVisibility(View.GONE);
  564.         }else
  565.         {
  566.             postNewActivity.isCameraPermissionGranted =false;
  567.             //main_Camera_container.setVisibility(View.GONE);
  568.             //bottom_layout.setVisibility(View.GONE);
  569.             premission_denined.setVisibility(View.VISIBLE);
  570.         }
  571.     }
  572.     /**
  573.      * <h2>reopenCamera</h2>
  574.      * <P>
  575.      *     Reopening the camera on switch of the camera.
  576.      * </P>*/
  577.     public void reopenCamera()
  578.     {
  579.         if (mTextureView.isAvailable())
  580.         {
  581.             openCamera(mTextureView.getWidth(), mTextureView.getHeight());
  582.         } else
  583.         {
  584.             mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
  585.         }
  586.     }
  587.  
  588.     /**
  589.      * <h2>askFor_Phone_Permission</h2>
  590.      * <P>
  591.      *  Method is going to ask for phone permission .
  592.      *  it is required for the read phone state in android.
  593.      * </P>*/
  594.     public void askFor_Phone_Permission(String tag)
  595.     {
  596.         ArrayList<App_permission_23.Permission> permissions =new ArrayList<>();
  597.  
  598.         App_permission_23.askWriteExternalStoragePermission(getActivity());
  599.  
  600.         System.out.println(tag.equalsIgnoreCase(CAMERA_TAG));
  601.  
  602.         if(tag.equalsIgnoreCase(CAMERA_TAG))
  603.         {
  604.             permissions.add(App_permission_23.Permission.CAMERA);
  605.             app_permission_23.getPermission_for_Sup_v4Fragment(CAMERA_TAG,permissions,parentactivity,this,this);
  606.         }else if(tag.equalsIgnoreCase(RECORDER_TAG))
  607.         {
  608.             permissions.add(App_permission_23.Permission.CAMERA);
  609.             permissions.add(App_permission_23.Permission.RECORD_AUDIO);
  610.             permissions.add(App_permission_23.Permission.WRITE_EXTERNAL_STORAGE);
  611.             app_permission_23.getPermission_for_Sup_v4Fragment(CAMERA_TAG,permissions,parentactivity,this,this);
  612.         }
  613.     }
  614.  
  615.  
  616.  
  617.  
  618.  
  619.     /**
  620.      * Sets up member variables related to camera.
  621.      * @param width  The width of available size for camera preview
  622.      * @param height The height of available size for camera preview
  623.      */
  624.     private void setUpCameraOutputs(int width, int height) {
  625.  
  626.         System.out.println("Setup camera outputs.");
  627.         try {
  628.             CameraCharacteristics characteristics = manager.getCameraCharacteristics(mCameraId);
  629.             StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
  630.  
  631.             assert map != null;
  632.  
  633.             Size largest = Collections.max(
  634.                     Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)),
  635.                     new CompareSizesByArea());
  636.  
  637.             mVideoSize = chooseVideoSize(map.getOutputSizes(MediaRecorder.class)); //640x480
  638.  
  639.             mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class),
  640.                     width, height, mVideoSize);
  641.             mImageReader = ImageReader.newInstance(largest.getWidth(), largest.getHeight(),
  642.                     ImageFormat.JPEG, /*maxImages*/2);
  643.             mImageReader.setOnImageAvailableListener(mOnImageAvailableListener, mBackgroundHandler);
  644.             int displayRotation =parentactivity.getWindowManager().getDefaultDisplay().getRotation();
  645.             mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
  646.             boolean swappedDimensions = false;
  647.  
  648.             switch (displayRotation) {
  649.                 case Surface.ROTATION_0:
  650.                 case Surface.ROTATION_180:
  651.                     if (mSensorOrientation == 90 || mSensorOrientation == 270)
  652.                     {
  653.                         swappedDimensions = true;
  654.                     }
  655.                     break;
  656.                 case Surface.ROTATION_90:
  657.                 case Surface.ROTATION_270:
  658.                     if (mSensorOrientation == 0 || mSensorOrientation == 180)
  659.                     {
  660.                         swappedDimensions = true;
  661.                     }
  662.                     break;
  663.                 default:
  664.             }
  665.  
  666.             Point displaySize = new Point();
  667.             parentactivity.getWindowManager().getDefaultDisplay().getSize(displaySize);
  668.             int rotatedPreviewWidth = width;
  669.             int rotatedPreviewHeight = height;
  670.             int maxPreviewWidth = displaySize.x;
  671.             int maxPreviewHeight = displaySize.y;
  672.  
  673.             if (swappedDimensions) {
  674.                 rotatedPreviewWidth = height;
  675.                 rotatedPreviewHeight = width;
  676.                 maxPreviewWidth = displaySize.y;
  677.                 maxPreviewHeight = displaySize.x;
  678.             }
  679.  
  680.             if (maxPreviewWidth > MAX_PREVIEW_WIDTH) {
  681.                 maxPreviewWidth = MAX_PREVIEW_WIDTH;
  682.             }
  683.             if (maxPreviewHeight > MAX_PREVIEW_HEIGHT) {
  684.                 maxPreviewHeight = MAX_PREVIEW_HEIGHT;
  685.             }
  686.  
  687.             mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class),
  688.                     rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth,
  689.                     maxPreviewHeight, mVideoSize);
  690.  
  691.             int orientation = getResources().getConfiguration().orientation;
  692.             if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
  693.                 mTextureView.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight());
  694.             } else {
  695.                 mTextureView.setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth());
  696.             }
  697.             Boolean available = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
  698.             mFlashSupported = available == null ? false : available;
  699.  
  700.         } catch (IllegalArgumentException e) {
  701.             e.printStackTrace();
  702.         }
  703.         catch (CameraAccessException | NullPointerException e) {
  704.             e.printStackTrace();
  705.         }
  706.     }
  707.  
  708.     /**
  709.      * Opens the camera specified by {@link CameraFragment_Ap21#mCameraId}.
  710.      */
  711.     private void openCamera(int width, int height)
  712.     {
  713.         if (ContextCompat.checkSelfPermission(parentactivity, Manifest.permission.CAMERA)
  714.                 != PackageManager.PERMISSION_GRANTED) {
  715.             System.out.println("Camera rights not allowed!");
  716.             return;
  717.         }
  718.         setUpCameraOutputs(width, height);
  719.         configureTransform(width, height);
  720.         try {
  721.             if (!mCameraOpenCloseLock.tryAcquire(5000, TimeUnit.MILLISECONDS))
  722.             {
  723.                 throw new RuntimeException("Time out waiting to lock camera opening.");
  724.             }
  725.             manager.openCamera(mCameraId, mStateCallback, mBackgroundHandler);
  726.         } catch (CameraAccessException e) {
  727.             e.printStackTrace();
  728.  
  729.         } catch (InterruptedException e) {
  730.             throw new RuntimeException("Interrupted while trying to lock camera opening.", e);
  731.         }
  732.     }
  733.  
  734.     /*
  735.     * handling the pager using object.*/
  736.     public void scrollFake_pager(int position)
  737.     {
  738.         if(fake_pager!=null)
  739.         {
  740.             fake_pager.setCurrentItem(position,true);
  741.         }
  742.     }
  743.     /**
  744.      * <h2>handel_Fake_pager</h2>
  745.      * <P>
  746.      *      Handel the camera to video tab movement in .
  747.      *      like Instagaram.
  748.      * </P>*/
  749.     private void handel_Fake_pager()
  750.     {
  751.         Post_view_fake_pager_adp fake_pager_adp = new Post_view_fake_pager_adp(getChildFragmentManager());
  752.         fake_pager.setAdapter(fake_pager_adp);
  753.         fake_pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
  754.             @Override
  755.             public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
  756.             {
  757.                 postNewActivity.handelTab_Scroll(position+1,positionOffset);
  758.             }
  759.             @Override
  760.             public void onPageSelected(int position)
  761.             {
  762.                 isVideo_active = position == 1;
  763.                 postNewActivity.page_position=position+1;
  764.                 postNewActivity.handel_Page_selection( postNewActivity.page_position);
  765.  
  766.             }
  767.             @Override
  768.             public void onPageScrollStateChanged(int state) {}
  769.         });
  770.     }
  771.  
  772.     /**
  773.      * Closes the current {@link CameraDevice}.
  774.      */
  775.     private void closeCamera()
  776.     {
  777.         try
  778.         {
  779.             mCameraOpenCloseLock.acquire();
  780.             if (null != mCaptureSession)
  781.             {
  782.                 mCaptureSession.close();
  783.                 mCaptureSession = null;
  784.             }
  785.             if (null != mCameraDevice)
  786.             {
  787.                 mCameraDevice.close();
  788.                 mCameraDevice = null;
  789.             }
  790.             if (null != mMediaRecorder) {
  791.                 mMediaRecorder.release();
  792.                 mMediaRecorder = null;
  793.             }
  794.             if (null != mImageReader)
  795.             {
  796.                 mImageReader.close();
  797.                 mImageReader = null;
  798.             }
  799.         } catch (Exception e)
  800.         {
  801.             e.printStackTrace();
  802.         } finally
  803.         {
  804.             mCameraOpenCloseLock.release();
  805.         }
  806.     }
  807.  
  808.  
  809.  
  810.  
  811.  
  812.     /**
  813.      * Starts a background thread and its {@link Handler}.
  814.      */
  815.     private void startBackgroundThread()
  816.     {
  817.         mBackgroundThread = new HandlerThread("StarMeCameraBackground");
  818.         mBackgroundThread.start();
  819.         mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
  820.     }
  821.     /**
  822.      * Stops the background thread and its {@link Handler}.
  823.      */
  824.     private void stopBackgroundThread()
  825.     {
  826.         if(mBackgroundThread!=null)
  827.         {
  828.             mBackgroundThread.quitSafely();
  829.         }
  830.         try {
  831.             if(mBackgroundThread!=null)
  832.             mBackgroundThread.join();
  833.             mBackgroundThread = null;
  834.             mBackgroundHandler = null;
  835.         } catch (Exception e) {}
  836.     }
  837.  
  838.     /**
  839.      * Creates a new {@link CameraCaptureSession} for camera preview.
  840.      */
  841.     private void createCameraPreviewSession()
  842.     {
  843.         if (null == mCameraDevice || !mTextureView.isAvailable() || null == mPreviewSize) {
  844.             return;
  845.         }
  846.         try
  847.         {
  848.             closePreviewSession();
  849.             SurfaceTexture texture = mTextureView.getSurfaceTexture();
  850.             assert texture != null;
  851.             texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
  852.             Surface surface = new Surface(texture);
  853.             mPreviewRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
  854.             mPreviewRequestBuilder.addTarget(surface);
  855.             mCameraDevice.createCaptureSession(Arrays.asList(surface, mImageReader.getSurface()),
  856.                     new CameraCaptureSession.StateCallback() {
  857.  
  858.                         @Override
  859.                         public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession)
  860.                         {
  861.                             if (null == mCameraDevice) {
  862.                                 return;
  863.                             }
  864.                             mCaptureSession = cameraCaptureSession;
  865.  
  866.                             try {
  867.                                 mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE,
  868.                                         CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
  869.                                 mPreviewRequest = mPreviewRequestBuilder.build();
  870.                                 mCaptureSession.setRepeatingRequest(mPreviewRequest,
  871.                                         mCaptureCallback, mBackgroundHandler);
  872.                             } catch (Exception e) {
  873.                                 e.printStackTrace();
  874.                             }
  875.                         }
  876.  
  877.                         @Override
  878.                         public void onConfigureFailed(
  879.                                 @NonNull CameraCaptureSession cameraCaptureSession)
  880.                         {
  881.                             showToast("Failed to configure camera.");
  882.                         }
  883.                     }, null
  884.             );
  885.         } catch (Exception e) {
  886.             e.printStackTrace();
  887.         }
  888.     }
  889.     /**
  890.      * Configures the necessary {@link Matrix} transformation to `mTextureView`.
  891.      * This method should be called after the camera preview size is determined in
  892.      * setUpCameraOutputs and also the size of `mTextureView` is fixed.
  893.      * @param viewWidth  The width of `mTextureView`
  894.      * @param viewHeight The height of `mTextureView`
  895.      */
  896.     private void configureTransform(int viewWidth, int viewHeight) {
  897.         if (null == mTextureView || null == mPreviewSize || null == parentactivity) {
  898.             return;
  899.         }
  900.         int rotation =parentactivity.getWindowManager().getDefaultDisplay().getRotation();
  901.         Matrix matrix = new Matrix();
  902.         RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
  903.         RectF bufferRect = new RectF(0, 0, mPreviewSize.getHeight(), mPreviewSize.getWidth());
  904.         float centerX = viewRect.centerX();
  905.         float centerY = viewRect.centerY();
  906.         if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) {
  907.             bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
  908.             matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
  909.             float scale = Math.max(
  910.                     (float) viewHeight / mPreviewSize.getHeight(),
  911.                     (float) viewWidth / mPreviewSize.getWidth());
  912.             matrix.postScale(scale, scale, centerX, centerY);
  913.             matrix.postRotate(90 * (rotation - 2), centerX, centerY);
  914.         } else if (Surface.ROTATION_180 == rotation) {
  915.             matrix.postRotate(180, centerX, centerY);
  916.         }
  917.         mTextureView.setTransform(matrix);
  918.     }
  919.     /**
  920.      * Initiate a still image capture.
  921.      */
  922.     private void takePicture() {
  923.         lockFocus();
  924.     }
  925.  
  926.     /**
  927.      * Lock the focus as the first step for a still image capture.
  928.      */
  929.     private void lockFocus()
  930.     {
  931.         try
  932.         {
  933.             mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER,
  934.                     CameraMetadata.CONTROL_AF_TRIGGER_START);
  935.             mState = STATE_WAITING_LOCK;
  936.             if(mCameraId.equals(Camera_Flash.FACING_BACK))
  937.             {
  938.                 mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback,
  939.                         mBackgroundHandler);
  940.             }else
  941.             {
  942.                 captureStillPicture();
  943.             }
  944.         } catch (Exception e)
  945.         {
  946.             e.printStackTrace();
  947.         }
  948.     }
  949.  
  950.     /**
  951.      * Run the precapture sequence for capturing a still image. This method should be called when
  952.      * we get a response in {@link #mCaptureCallback} from {@link #lockFocus()}.
  953.      */
  954.     private void runPrecaptureSequence() {
  955.         try {
  956.             // This is how to tell the camera to trigger.
  957.             mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER,
  958.                     CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER_START);
  959.             // Tell #mCaptureCallback to wait for the precapture sequence to be set.
  960.             mState = STATE_WAITING_PRECAPTURE;
  961.             mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback,
  962.                     mBackgroundHandler);
  963.         } catch (CameraAccessException e) {
  964.             e.printStackTrace();
  965.         }
  966.     }
  967.  
  968.     /**
  969.      * Capture a still picture. This method should be called when we get a response in
  970.      * {@link #mCaptureCallback} from both {@link #lockFocus()}.
  971.      */
  972.     private void captureStillPicture() {
  973.         try {
  974.             if (null == parentactivity || null == mCameraDevice) {
  975.                 return;
  976.             }
  977.             final CaptureRequest.Builder captureBuilder =
  978.                     mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
  979.             captureBuilder.addTarget(mImageReader.getSurface());
  980.             captureBuilder.set(CaptureRequest.CONTROL_AF_MODE,
  981.                     CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
  982.             int rotation =parentactivity.getWindowManager().getDefaultDisplay().getRotation();
  983.             captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, getOrientation(rotation));
  984.             CameraCaptureSession.CaptureCallback CaptureCallback = new CameraCaptureSession.CaptureCallback()
  985.             {
  986.  
  987.                 @Override
  988.                 public void onCaptureCompleted(@NonNull CameraCaptureSession session,
  989.                                                @NonNull CaptureRequest request,
  990.                                                @NonNull TotalCaptureResult result)
  991.                 {
  992.                     unlockFocus();
  993.                 }
  994.             };
  995.             mCaptureSession.stopRepeating();
  996.             mCaptureSession.capture(captureBuilder.build(),CaptureCallback, null);
  997.             unlockFocus();
  998.         } catch (CameraAccessException e) {
  999.             e.printStackTrace();
  1000.         }
  1001.     }
  1002.  
  1003.     /**
  1004.      * Retrieves the JPEG orientation from the specified screen rotation.
  1005.      *
  1006.      * @param rotation The screen rotation.
  1007.      * @return The JPEG orientation (one of 0, 90, 270, and 360)
  1008.      */
  1009.     private int getOrientation(int rotation) {
  1010.         // Sensor orientation is 90 for most devices, or 270 for some devices (eg. Nexus 5X)
  1011.         // We have to take that into account and rotate JPEG properly.
  1012.         // For devices with orientation of 90, we simply return our mapping from ORIENTATIONS.
  1013.         // For devices with orientation of 270, we need to rotate the JPEG 180 degrees.
  1014.         return (ORIENTATIONS.get(rotation) + mSensorOrientation + 270) % 360;
  1015.     }
  1016.  
  1017.     /**
  1018.      * Unlock the focus. This method should be called when still image capture sequence is
  1019.      * finished.
  1020.      */
  1021.     private void unlockFocus()
  1022.     {
  1023.         try {
  1024.             mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER,
  1025.                     CameraMetadata.CONTROL_AF_TRIGGER_CANCEL);
  1026.             mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback,
  1027.                     mBackgroundHandler);
  1028.             mState = STATE_PREVIEW;
  1029.             mCaptureSession.setRepeatingRequest(mPreviewRequest, mCaptureCallback, mBackgroundHandler);
  1030.         } catch (Exception e)
  1031.         {
  1032.             e.printStackTrace();
  1033.         }
  1034.     }
  1035.  
  1036.     @Override
  1037.     public void onClick(View view) {
  1038.         switch (view.getId()) {
  1039.  
  1040.             case R.id.take_photo:
  1041.  
  1042.                 toggleRecording();
  1043.                 take_photo.setEnabled(false);
  1044.                 new Handler().postDelayed(new Runnable() {
  1045.                     @Override
  1046.                     public void run() {
  1047.                         take_photo.setEnabled(true);
  1048.                     }
  1049.                 }, 3000);
  1050.         }
  1051.     }
  1052.  
  1053.     private void toggleRecording() {
  1054.  
  1055.         System.out.println("Toggle recording video: " + !mIsRecordingVideo);
  1056.  
  1057.         if (!mIsRecordingVideo) {
  1058.             handel_button_Selected(true);
  1059.             startRecordingVideo();
  1060.         }
  1061.         else {
  1062.             handel_button_Selected(false);
  1063.             stopRecordingVideo();
  1064.         }
  1065.     }
  1066.  
  1067.  
  1068.     /**
  1069.      * Start recording user input and translating it into pitches, uses 'TarsosDSP'
  1070.      */
  1071.     private void startRecordingUserInput() {
  1072.         System.out.println("Start recording audio...");
  1073.         audioRecorder.record(new AudioRecordingHandler() {
  1074.             @Override
  1075.             public void handlePitch(float pitch) {
  1076.  
  1077.                 listener.onPitchChanged(pitch);
  1078.             }
  1079.  
  1080.             @Override
  1081.             public void finishedRecording(File aacFile) {
  1082.                 System.out.println("Encoding finished!");
  1083.                 aacfile = aacFile;
  1084.             }
  1085.         });
  1086.         System.out.println("...recording audio");
  1087.     }
  1088.  
  1089.     public void startRecordingVideo() {
  1090.  
  1091.         if (null == mCameraDevice || !mTextureView.isAvailable() || null == mPreviewSize) {
  1092.             return;
  1093.         }
  1094.  
  1095.         try {
  1096.             System.out.println("Start recording video...");
  1097.  
  1098.             closePreviewSession();
  1099.             setUpMediaRecorder();
  1100.  
  1101.             SurfaceTexture texture = mTextureView.getSurfaceTexture();
  1102.             assert texture != null;
  1103.             texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
  1104.  
  1105.             mPreviewRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_RECORD);
  1106.             Surface mRecorderSurface = mMediaRecorder.getSurface();
  1107.             List<Surface> surfaces = new ArrayList<>();
  1108.             Surface previewSurface = new Surface(texture);
  1109.             surfaces.add(previewSurface);
  1110.             mPreviewRequestBuilder.addTarget(previewSurface);
  1111.  
  1112.             surfaces.add(mRecorderSurface);
  1113.             mPreviewRequestBuilder.addTarget(mRecorderSurface);
  1114.  
  1115.             take_photo.setActivated(true);
  1116.             start_Timer();
  1117.             listener.onCameraRecording(); //Send out camera recording signal
  1118.  
  1119.             mCameraDevice.createCaptureSession(surfaces, new CameraCaptureSession.StateCallback() {
  1120.  
  1121.                 @Override
  1122.                 public void onReady(@NonNull CameraCaptureSession session) {
  1123.                     System.out.println("Ready...");
  1124.                     super.onReady(session);
  1125.                 }
  1126.  
  1127.                 @Override
  1128.                 public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
  1129.                     mCaptureSession = cameraCaptureSession;
  1130.                     updatePreview();
  1131.  
  1132.                     parentactivity.runOnUiThread(new Runnable() {
  1133.  
  1134.                         @Override
  1135.                         public void run() {
  1136.                             System.out.println("Start recording on UI Thread!");
  1137.  
  1138.                             if(mNextVideoAbsolutePath!=null) {
  1139.                                 record_file_paths.add(mNextVideoAbsolutePath);
  1140.                             }
  1141.                             mIsRecordingVideo = true;
  1142.                             mMediaRecorder.start();
  1143.  
  1144.                             startRecordingUserInput();
  1145.                             recorded_time.setVisibility(View.VISIBLE);
  1146.                             handel_bottom_View(false);
  1147.                         }
  1148.                     });
  1149.                 }
  1150.  
  1151.                 @Override
  1152.                 public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
  1153.                     if (null != parentactivity) {
  1154.                         Toast.makeText(parentactivity, "Failed to configure camera.", Toast.LENGTH_SHORT).show();
  1155.                     }
  1156.                 }
  1157.             }, mBackgroundHandler);
  1158.         } catch (CameraAccessException | IOException e) {
  1159.             e.printStackTrace();
  1160.         }
  1161.     }
  1162.  
  1163.  
  1164.     /**
  1165.      * Setup video recorder
  1166.      * @throws IOException
  1167.      */
  1168.     private void setUpMediaRecorder() throws IOException {
  1169.         if (null == parentactivity) {
  1170.             return;
  1171.         }
  1172.  
  1173.         mMediaRecorder = new UMediaRecorder();
  1174.         mMediaRecorder.setStateListener(new UMediaRecorder.UMediaRecorderStateListener() {
  1175.             @Override
  1176.             public void onStop() {
  1177.             }
  1178.         });
  1179.         mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
  1180.         mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
  1181.  
  1182.         mNextVideoAbsolutePath = getVideoFilePath();
  1183.         mMediaRecorder.setOutputFile(mNextVideoAbsolutePath);
  1184.  
  1185.         mMediaRecorder.setVideoFrameRate(30);
  1186.         mMediaRecorder.setVideoEncodingBitRate(500000); //Recomennded 500k
  1187.  
  1188.         mMediaRecorder.setVideoSize(mVideoSize.getWidth(), mVideoSize.getHeight());
  1189.         mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
  1190.  
  1191.         int rotation = parentactivity.getWindowManager().getDefaultDisplay().getRotation();
  1192.  
  1193.         switch (mSensorOrientation) {
  1194.             case SENSOR_ORIENTATION_DEFAULT_DEGREES:
  1195.                 mMediaRecorder.setOrientationHint(DEFAULT_ORIENTATIONS.get(rotation));
  1196.                 break;
  1197.             case SENSOR_ORIENTATION_INVERSE_DEGREES:
  1198.                 mMediaRecorder.setOrientationHint(INVERSE_ORIENTATIONS.get(rotation));
  1199.                 break;
  1200.         }
  1201.  
  1202.         try {
  1203.             mMediaRecorder.prepare();
  1204.         } catch (IllegalStateException ex) {
  1205.             ex.printStackTrace();
  1206.         }
  1207.     }
  1208.  
  1209.     public void stopRecordingVideo() {
  1210.  
  1211.         stop_record_Time();
  1212.         if(!mIsRecordingVideo) { return; }
  1213.  
  1214.         mIsRecordingVideo = false;
  1215.         System.out.println("Stop video recording.");
  1216.         take_photo.setActivated(false);
  1217.         try {
  1218.  
  1219.             audioRecorder.stop();
  1220.             mCaptureSession.stopRepeating();
  1221.             mCaptureSession.abortCaptures();
  1222.             mMediaRecorder.stop();
  1223.             mMediaRecorder.release();
  1224.             closeCamera();
  1225.  
  1226.             tempVideo = new File(mNextVideoAbsolutePath);
  1227.  
  1228.             System.out.println("Final video length: " + tempVideo.length());
  1229.             //mMediaRecorder.reset();
  1230.             listener.onCameraStop(tempVideo, aacfile, previous_recorded_time);
  1231.         } catch (Exception e) {
  1232.             System.out.println("Error stopping media recorder");
  1233.             e.printStackTrace();
  1234.         }
  1235.  
  1236.         mNextVideoAbsolutePath = null;
  1237. //        closeCamera();
  1238.  
  1239.         if (mTextureView.isAvailable()) {
  1240.             //openCamera(mTextureView.getWidth(), mTextureView.getHeight());
  1241.         } else {
  1242.             //handel else part
  1243.         }
  1244.     }
  1245.  
  1246.     private String getVideoFilePath() {
  1247.         File file = postNewActivity.folder_handler.createFile_for_Video();
  1248.         return file.getPath();
  1249.     }
  1250.     /**
  1251.      * Update the camera preview. {@link} needs to be called in advance.
  1252.      */
  1253.     private void updatePreview() {
  1254.         if (null == mCameraDevice) {
  1255.             return;
  1256.         }
  1257.         try {
  1258.             setUpCaptureRequestBuilder(mPreviewRequestBuilder);
  1259.             mCaptureSession.setRepeatingRequest(mPreviewRequestBuilder.build(), null, mBackgroundHandler);
  1260.         } catch (CameraAccessException e) {
  1261.             e.printStackTrace();
  1262.         }
  1263.     }
  1264.  
  1265.     private void setUpCaptureRequestBuilder(CaptureRequest.Builder builder) {
  1266.         builder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
  1267.     }
  1268.  
  1269.     private void closePreviewSession() {
  1270.         if (mCaptureSession != null) {
  1271.             mCaptureSession.close();
  1272.             mCaptureSession = null;
  1273.         }
  1274.     }
  1275.  
  1276.     /**
  1277.      * In this sample, we choose a video size with 3x4 aspect ratio. Also, we don't use sizes
  1278.      * larger than 1080p, since MediaRecorder cannot handle such a high-resolution video.
  1279.      *
  1280.      * @param choices The list of available sizes
  1281.      * @return The video size
  1282.      */
  1283.     private static Size chooseVideoSize(Size[] choices)
  1284.     {
  1285.         for (Size size : choices) {
  1286.             if (size.getWidth() == size.getHeight() * 4 / 3 && size.getWidth() <= 720) {
  1287.                 return size;
  1288.             }
  1289.         }
  1290.         return choices[choices.length - 1];
  1291.     }
  1292.  
  1293.  
  1294.     @Override
  1295.     public void onPermissionGranted(boolean isAllGranted, String tag)
  1296.     {
  1297.         if(isAllGranted&&tag.equalsIgnoreCase(CAMERA_TAG))
  1298.         {
  1299.             permission_layout_handeler(true);
  1300.         }else if(isAllGranted&&tag.equalsIgnoreCase(RECORDER_TAG))
  1301.         {
  1302.             permission_layout_handeler(true);
  1303.         }
  1304.     }
  1305.  
  1306.     @Override
  1307.     public void onPermissionDenied(ArrayList<String> deniedPermission, String tag)
  1308.     {
  1309.         String[] stringArray = deniedPermission.toArray(new String[0]);
  1310.         if(tag.equalsIgnoreCase(CAMERA_TAG))
  1311.         {
  1312.             app_permission_23.ask_permission_directory(stringArray);
  1313.         }else if(tag.equalsIgnoreCase(RECORDER_TAG))
  1314.         {
  1315.             app_permission_23.ask_permission_directory(stringArray);
  1316.         }
  1317.     }
  1318.  
  1319.     @Override
  1320.     public void onPermissionRotation(ArrayList<String> rotationPermission, String tag)
  1321.     {
  1322.         isTurn_button_click=false;
  1323.         String[] permission = rotationPermission.toArray(new String[0]);
  1324.         app_permission_23.ask_permission_rotational(permission);
  1325.     }
  1326.     @Override
  1327.     public void onPermissionPermanent_Denied(String tag)
  1328.     {
  1329.         if(tag.equalsIgnoreCase(CAMERA_TAG)||tag.equalsIgnoreCase(RECORDER_TAG))
  1330.         {
  1331.             if(isTurn_button_click)
  1332.             {
  1333.                 open_Setting_dialog();
  1334.             }else
  1335.             {
  1336.                 permission_layout_handeler(false);
  1337.             }
  1338.             isTurn_button_click=false;
  1339.         }
  1340.     }
  1341.  
  1342.  
  1343.  
  1344.     public void handel_Operation(int op_number)
  1345.     {
  1346.         switch (op_number)
  1347.         {
  1348.             case 0:
  1349.             {
  1350.                 takePicture();
  1351.                 break;
  1352.             }
  1353.             case 1:
  1354.             {
  1355.                 isTurn_button_click=true;
  1356.                 if(isVideo_active)
  1357.                 {
  1358.                     askFor_Phone_Permission(RECORDER_TAG);
  1359.                 }else
  1360.                 {
  1361.                     askFor_Phone_Permission(CAMERA_TAG);
  1362.                 }
  1363.             }
  1364.         }
  1365.     }
  1366.     /**
  1367.      * Saves a JPEG {@link Image} into the specified {@link File}.
  1368.      */
  1369.     private class ImageSaver implements Runnable
  1370.     {
  1371.  
  1372.  
  1373.         private final Image mImage;
  1374.         private final File mFile;
  1375.         ImageSaver(Image image) {
  1376.             mImage = image;
  1377.             mFile = postNewActivity.folder_handler.createFile_for_Image();
  1378.         }
  1379.         @Override
  1380.         public void run() {
  1381.  
  1382.             System.out.println("record image!");
  1383.  
  1384.             ByteBuffer buffer = mImage.getPlanes()[0].getBuffer();
  1385.             byte[] bytes = new byte[buffer.remaining()];
  1386.             buffer.get(bytes);
  1387.             FileOutputStream output = null;
  1388.             try {
  1389.                 output = new FileOutputStream(mFile);
  1390.                 output.write(bytes);
  1391.             } catch (IOException e)
  1392.             {
  1393.                 e.printStackTrace();
  1394.             } finally
  1395.             {
  1396.                 mImage.close();
  1397.                 if (null != output)
  1398.                 {
  1399.                     try
  1400.                     {
  1401.                         output.close();
  1402.                     } catch (IOException e)
  1403.                     {
  1404.                         e.printStackTrace();
  1405.                     }}
  1406.             }
  1407.             openFilter(mFile);
  1408.         }
  1409.     }
  1410.  
  1411.     private void openFilter(File file) {
  1412.         isForCapture=false;
  1413.         if(file.exists()&&file.length()>10) {
  1414.             postNewActivity.nextClick(false,file.getPath());
  1415.         } else {
  1416.             Toast.makeText(parentactivity,"Unable to store Image",Toast.LENGTH_SHORT).show();
  1417.         }
  1418.     }
  1419.  
  1420.     /**
  1421.      * Compares two {@code Size}s based on their areas.
  1422.      */
  1423.     private static class CompareSizesByArea implements Comparator<Size> {
  1424.  
  1425.         @Override
  1426.         public int compare(Size lhs, Size rhs) {
  1427.             // We cast here to ensure the multiplications won't overflow
  1428.             return Long.signum((long) lhs.getWidth() * lhs.getHeight() -
  1429.                     (long) rhs.getWidth() * rhs.getHeight());
  1430.         }
  1431.     }
  1432.  
  1433.     /**
  1434.      * Resets recording timer
  1435.      */
  1436.     private void resetRecordingTimer() {
  1437.         recorded_time.setText(String.format("0.%s", String.format(Locale.ENGLISH,"%02d", 0)));
  1438.     }
  1439.  
  1440.     /**
  1441.      * Starts video record timer.
  1442.      */
  1443.     private void start_Timer() {
  1444.         resetRecordingTimer();
  1445.         timer=new Timer();
  1446.         timer.schedule(new TimerTask() {
  1447.             @Override
  1448.             public void run() {
  1449.                 parentactivity.runOnUiThread(new Runnable() {
  1450.                     @Override
  1451.                     public void run() {
  1452.                         previous_recorded_time=previous_recorded_time+1;
  1453.                         parentactivity.runOnUiThread(new Runnable() {
  1454.                             @Override
  1455.                             public void run() {
  1456.                                 record_progressBar.setProgress(previous_recorded_time);
  1457.                                 recorded_time.setText(String.format(secondsToString(previous_recorded_time)));
  1458.                             }
  1459.                         });
  1460.                     }
  1461.                 });
  1462.             }
  1463.         }, 0, 1000);
  1464.     }
  1465.  
  1466.     private void stop_record_Time() {
  1467.         if (timer != null) {
  1468.             timer.cancel();
  1469.         }
  1470.     }
  1471.  
  1472.     private String secondsToString(int pTime) {
  1473.         return String.format("%02d:%02d", pTime / 60, pTime % 60);
  1474.     }
  1475.  
  1476.     /*
  1477.     * deleting the video recorded file.*/
  1478.     public void delete_Recorded_file()
  1479.     {
  1480.         if(!isRecord_file_exist)
  1481.         {
  1482.             return;
  1483.         }
  1484.         for(String file_path: record_file_paths)
  1485.         {
  1486.             File file=new File(file_path);
  1487.             if(file.exists())
  1488.             {
  1489.                 boolean deleted=file.delete();
  1490.             }
  1491.         }
  1492.  
  1493.         record_file_paths.clear();
  1494.         handel_bottom_View(true);
  1495.     }
  1496.  
  1497.  
  1498.  
  1499.     public void collect_Recorded_Videos()
  1500.     {
  1501.         if(record_file_paths.size()>0)
  1502.         {
  1503.             postNewActivity.circle_progress_bar_dialog.set_Progress_title("Merging file..");
  1504.             postNewActivity.circle_progress_bar_dialog.get_Circle_Progress_bar(parentactivity).show();
  1505.             String []files=record_file_paths.toArray(new String[record_file_paths.size()]);
  1506.             File_merger.getInstance().mergeMediaFiles(parentactivity,false, files,new File_merger.Merger_callback()
  1507.             {
  1508.                 @Override
  1509.                 public void onSuccess(String file_parh)
  1510.                 {
  1511.                     postNewActivity.circle_progress_bar_dialog.get_Circle_Progress_bar(parentactivity).dismiss();
  1512.                     handel_bottom_View(true);
  1513.                     /*
  1514.                       * Loading the video frg.*/
  1515.                     postNewActivity.load_fragment(2,file_parh,"");
  1516.  
  1517.                 }
  1518.                 @Override
  1519.                 public void onError(String error)
  1520.                 {
  1521.                     postNewActivity.circle_progress_bar_dialog.get_Circle_Progress_bar(parentactivity).dismiss();
  1522.                     Toast.makeText(parentactivity,error,Toast.LENGTH_SHORT).show();
  1523.                 }
  1524.             });
  1525.         }
  1526.     }
  1527.  
  1528.     public void handel_bottom_View(boolean isVisible)
  1529.     {
  1530.         /*if(isVisible)
  1531.         {
  1532.             fake_pager.setPagingEnabled(true);
  1533.             //postNewActivity.newPost_scrollView.setPagingEnabled(true);
  1534.             postNewActivity.isVideo_Recorded=false;
  1535.             postNewActivity.next_text_layout.setVisibility(View.GONE);
  1536.             isRecord_file_exist=false;
  1537.             //postNewActivity.delete_video.setVisibility(View.GONE);
  1538.             previous_recorded_time=0;
  1539.             parentactivity.runOnUiThread(new Runnable() {
  1540.                 @Override
  1541.                 public void run()
  1542.                 {
  1543.                     record_progressBar.setProgress(1);
  1544.                     recorded_time.setVisibility(View.INVISIBLE);
  1545.                 }
  1546.             });
  1547.             bottom_Up_Slide();
  1548.         }else
  1549.         {
  1550.             fake_pager.setPagingEnabled(false);
  1551.             //postNewActivity.newPost_scrollView.setPagingEnabled(false);
  1552.             postNewActivity.isVideo_Recorded=true;
  1553.             postNewActivity.next_text_layout.setVisibility(View.VISIBLE);
  1554.             isRecord_file_exist=true;
  1555.             //postNewActivity.delete_video.setVisibility(View.VISIBLE);
  1556.             close_Page_Slide();
  1557.         }*/
  1558.     }
  1559.     /**
  1560.      * Showing  the hidden Tab bar and using android animation class and the
  1561.      * setting the visibility of the tabb layout as Visible .
  1562.      * {@link View#VISIBLE}.
  1563.      * @see  AnimationUtils#loadAnimation(Context, int)  */
  1564.     private void bottom_Up_Slide()
  1565.     {
  1566.         postNewActivity.post_tab_layout.setVisibility(View.VISIBLE);
  1567.         Animation animation_bottom_out = AnimationUtils.loadAnimation(parentactivity, R.anim.bottom_in_animation);
  1568.         animation_bottom_out.setAnimationListener(new Animation.AnimationListener()
  1569.         {
  1570.             @Override
  1571.             public void onAnimationStart(Animation animation)
  1572.             {}
  1573.             @Override
  1574.             public void onAnimationEnd(Animation animation)
  1575.             {
  1576.             }
  1577.             @Override
  1578.             public void onAnimationRepeat(Animation animation)
  1579.             {}
  1580.         });
  1581.         postNewActivity.post_tab_layout.setAnimation(animation_bottom_out);
  1582.     }
  1583.     /**
  1584.      * Hiding the Tab bar and using android animation class and the
  1585.      * setting the visibility of the tabb layout as Gone .
  1586.      * {@link View#GONE}.
  1587.      * @see  AnimationUtils#loadAnimation(Context, int)  */
  1588.     private void close_Page_Slide()
  1589.     {
  1590.         postNewActivity.post_tab_layout.setVisibility(View.GONE);
  1591.         Animation animation_bottom_out = AnimationUtils.loadAnimation(parentactivity, R.anim.bottom_down_animation);
  1592.         animation_bottom_out.setAnimationListener(new Animation.AnimationListener()
  1593.         {
  1594.             @Override
  1595.             public void onAnimationStart(Animation animation)
  1596.             {}
  1597.             @Override
  1598.             public void onAnimationEnd(Animation animation)
  1599.             {
  1600.             }
  1601.             @Override
  1602.             public void onAnimationRepeat(Animation animation)
  1603.             {}
  1604.         });
  1605.         postNewActivity.post_tab_layout.setAnimation(animation_bottom_out);
  1606.     }
  1607.     /**
  1608.      Rotating the camera switch button by 360 degree in
  1609.      using android Animation util.
  1610.      {@link AnimationUtils#loadAnimation(Context, int)}*/
  1611.     private void rotate_Camera_Switch_view()
  1612.     {
  1613.         Animation animation_bottom_out = AnimationUtils.loadAnimation(parentactivity, R.anim.rotate_view_animation);
  1614.         animation_bottom_out.setAnimationListener(new Animation.AnimationListener()
  1615.         {
  1616.             @Override
  1617.             public void onAnimationStart(Animation animation)
  1618.             {}
  1619.             @Override
  1620.             public void onAnimationEnd(Animation animation)
  1621.             {
  1622.             }
  1623.             @Override
  1624.             public void onAnimationRepeat(Animation animation)
  1625.             {}
  1626.         });
  1627.     }
  1628.     /**
  1629.      * <h2>animateShutter</h2>
  1630.      * <P>
  1631.      *    Animating a view on capture of image to show image capture.
  1632.      * </P>*/
  1633.     private void animateShutter()
  1634.     {
  1635.         mShutter.setVisibility(View.VISIBLE);
  1636.         mShutter.setAlpha(0.f);
  1637.         ObjectAnimator alphaInAnim = ObjectAnimator.ofFloat(mShutter, "alpha", 0f, 0.8f);
  1638.         alphaInAnim.setDuration(100);
  1639.         alphaInAnim.setStartDelay(100);
  1640.         alphaInAnim.setInterpolator(ACCELERATE_INTERPOLATOR);
  1641.  
  1642.         ObjectAnimator alphaOutAnim = ObjectAnimator.ofFloat(mShutter, "alpha", 0.8f, 0f);
  1643.         alphaOutAnim.setDuration(200);
  1644.         alphaOutAnim.setInterpolator(DECELERATE_INTERPOLATOR);
  1645.  
  1646.         AnimatorSet animatorSet = new AnimatorSet();
  1647.         animatorSet.playSequentially(alphaInAnim, alphaOutAnim);
  1648.         animatorSet.addListener(new AnimatorListenerAdapter() {
  1649.             @Override
  1650.             public void onAnimationEnd(Animator animation) {
  1651.                 mShutter.setVisibility(View.GONE);
  1652.             }
  1653.         });
  1654.         animatorSet.start();
  1655.     }
  1656.  
  1657.  
  1658.     /**
  1659.      * <h2>open_Setting_dialog</h2>
  1660.      * <P>
  1661.      *    Opening the setting page for the uer to set the permission and the
  1662.      *    user can togel the permission and handel provide permission to this app.
  1663.      * </P>*/
  1664.     private void open_Setting_dialog()
  1665.     {
  1666.         /*
  1667.          * closing the key pad.*/
  1668.         Utility.close_soft_input_keypad(parentactivity);
  1669.         Context context=parentactivity;
  1670.         android.support.v7.app.AlertDialog.Builder alertDialog = new android.support.v7.app.AlertDialog.Builder(context);
  1671.         LayoutInflater inflater = parentactivity.getLayoutInflater();
  1672.         @SuppressLint("InflateParams")
  1673.         View dialogView = inflater.inflate(R.layout.permission_denined_setting_layout,null);
  1674.         alertDialog.setView(dialogView);
  1675.  
  1676.         TextView header_title= dialogView.findViewById(R.id.heading_text);
  1677.         header_title.setTypeface(postNewActivity.RobotoRegular);
  1678.         TextView setting_click= dialogView.findViewById(R.id.setting_click);
  1679.         setting_click.setTypeface(postNewActivity.RobotoMedium);
  1680.         setting_click.setOnClickListener(new View.OnClickListener() {
  1681.             @Override
  1682.             public void onClick(View v)
  1683.             {
  1684.                 Intent intent = new Intent();
  1685.                 intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
  1686.                 Uri uri = Uri.fromParts("package",parentactivity.getPackageName(), null);
  1687.                 intent.setData(uri);
  1688.                 parentactivity.startActivity(intent);
  1689.  
  1690.                 if(postNewActivity.alert_dialog!=null) {
  1691.                     postNewActivity.alert_dialog.cancel();
  1692.                     postNewActivity.alert_dialog.dismiss();
  1693.                 }
  1694.             }
  1695.         });
  1696.         postNewActivity.alert_dialog = alertDialog.show();
  1697.         postNewActivity.alert_dialog.show();
  1698.     }
  1699.  
  1700.  
  1701.     public void setCameraActionListener(CameraFragmentActionListener listener) {
  1702.         this.listener = listener;
  1703.     }
  1704.  
  1705.     /** Interface for listener **/
  1706.     public interface CameraFragmentActionListener {
  1707.         void onCameraRecording();
  1708.         void onCameraStop(File outputFile, File aacFile, int recordingInSeconds);
  1709.         void onPitchChanged(float pitch);
  1710.     }
  1711.  
  1712.     public int getUserStarsForCurrentSong(){
  1713.         String tvValue = userScoreTextView.getText().toString();
  1714.  
  1715.         if (!tvValue.equals("")) {
  1716.             return Integer.parseInt(tvValue);
  1717.         }
  1718.  
  1719.         return 0;
  1720.     }
  1721.  
  1722.     /**
  1723.      * Change text on score text view
  1724.      * @param score
  1725.      */
  1726.     public void setSongScore(int score) {
  1727.         if (userScoreTextView != null && score > 0) {
  1728.             userScoreTextView.setText(String.valueOf(score));
  1729.         }
  1730.     }
  1731.  
  1732.  
  1733.  
  1734.  
  1735. }
Add Comment
Please, Sign In to add comment