اذهب إلى المحتوى

السؤال

نشر


@SuppressWarnings("ALL")
public class uploadved extends AppCompatActivity implements difroved.ExampleDialogeListener {
    TextView uploader;
    RoundedImageView geter;
    VideoView vedgetr;
    MediaController mc;
    File file;
    String wasfst;
    String mohtst;
    String qul;
    int progstat = 0;
    int w;
    int h;
    TextView shertved;
    ImageView ext, imgvedto;
    EditText edtanwan, edtwasf;
    Spinner spmraddafo;
    BottomSheetDialog bottomSheetDialog;
    private RequestQueue rQueue;
    private static final int SELECT_VIDEO_REQUEST = 0;
    public Uri videoUri;
    String displayName;
    String Path;
    ExecutorService service;
    String enwanvido;
    int fileLength;
    Context context;
    String URLphp = "https://elokhtboot.com/okt/Nashr/uploadved.php";
    boolean check = true;
    public
    Bitmap bitmap;
    ImageView trimVideo, slowmotion;
    TextView slowmotiontext;
    private ProgressBar progressBar;
    Dialog dila;
    Uri uritoupload;
    ////////////////ROTH test /////////////////////
    int videoResolution;

    Uri inputPath ;
    String outputPath;
    int width = 576;
    int height = 1024;

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

        geter = findViewById(R.id.geter);
        uploader = findViewById(R.id.uploader);
        vedgetr = findViewById(R.id.vedgetr);
        mc = new MediaController(uploadved.this);
        vedgetr.setMediaController(mc);
        geter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(uploadved.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {

                    selectVideo();
                } else {
                    ActivityCompat.requestPermissions(uploadved.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                }
            }
        });
        uploader.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (videoUri != null) {

                    bottomSheetDialog = new BottomSheetDialog(uploadved.this, R.style.BottomSheetDialogTheme2);
                    View va = LayoutInflater.from(uploadved.this)
                            .inflate(R.layout.veduploadbotorrsheet, uploadved.this.findViewById(R.id.btomCount));
                    bottomSheetDialog.getBehavior().setState(BottomSheetBehavior.STATE_EXPANDED);
                    v.setMinimumHeight(Resources.getSystem().getDisplayMetrics().heightPixels);
                    shertved = va.findViewById(R.id.shertved);
                    ext = va.findViewById(R.id.ext);
                    imgvedto = va.findViewById(R.id.imgvedto);
                    edtanwan = va.findViewById(R.id.edtanwan);
                    edtwasf = va.findViewById(R.id.edtwasf);
                    spmraddafo = va.findViewById(R.id.spmraddafo);

                    edtanwan.addTextChangedListener(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                        }

                        @Override
                        public void onTextChanged(CharSequence s, int start, int before, int count) {
                            enwanvido = edtanwan.getText().toString().trim();
                            Log.d("enwan", enwanvido);
                            int t = enwanvido.length();
                            if (t > 1) {
                                t = 1;
                            }
                            if (t > 40) {
                                t = 250;
                            }
                            if (t > 250) {
                                t = 250;
                            }
                            switch (t) {
                                case 0:
                                    edtanwan.setBackgroundResource(R.drawable.backwrong);
                                    shertved.setVisibility(View.GONE);
                                    Toast.makeText(uploadved.this, "يجب اضافة عنوان للفيديو", Toast.LENGTH_SHORT).show();
                                    break;
                                case 1:
                                    edtanwan.setBackgroundResource(R.drawable.edenwanved);
                                    shertved.setVisibility(View.VISIBLE);
                                    shertved.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            uploadvideo(displayName, videoUri);
                                        }
                                    });
                                    break;
                                case 250:
                                    edtanwan.setBackgroundResource(R.drawable.backwrong);
                                    shertved.setVisibility(View.GONE);
                                    Toast.makeText(uploadved.this, "عدد الاحرف اكثر من اللازم", Toast.LENGTH_SHORT).show();

                                    break;
                                default:
                                    edtanwan.setBackgroundResource(R.drawable.edenwanved);
                                    shertved.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            uploadvideo(displayName, videoUri);
                                        }
                                    });
                                    break;

                            }
                        }

                        @Override
                        public void afterTextChanged(Editable s) {

                        }
                    });
                    edtwasf.addTextChangedListener(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                        }

                        @Override
                        public void onTextChanged(CharSequence s, int start, int before, int count) {
                            wasfst = edtwasf.getText().toString().trim();
                            Log.d("enwan", wasfst);
                            int t = wasfst.length();
                            if (t > 1) {
                                t = 1;
                            }
                            if (t > 155) {
                                t = 155;
                            }

                            switch (t) {
                                case 0:
                                    edtwasf.setBackgroundResource(R.drawable.backwrong);
                                    shertved.setVisibility(View.GONE);
                                    break;
                                case 1:
                                    edtwasf.setBackgroundResource(R.drawable.edenwanved);
                                    shertved.setVisibility(View.VISIBLE);
                                    shertved.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            uploadvideo(displayName, videoUri);
                                        }
                                    });
                                    break;
                                case 250:
                                    edtwasf.setBackgroundResource(R.drawable.backwrong);
                                    shertved.setVisibility(View.GONE);
                                    break;
                                default:
                                    edtwasf.setBackgroundResource(R.drawable.edenwanved);
                                    shertved.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            uploadvideo(displayName, videoUri);
                                            ////Here is where the user can click to execute the upload order
                                        }
                                    });
                                    break;

                            }
                        }

                        @Override
                        public void afterTextChanged(Editable s) {

                        }
                    });

                    spmraddafo.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                            mohtst = parent.getItemAtPosition(position).toString();
                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {
                            mohtst = "غير ذلك";
                        }
                    });
                    Glide.with(imgvedto).load(videoUri).into(imgvedto);
                    ext.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            bottomSheetDialog.dismiss();
                        }
                    });
                    bottomSheetDialog.setContentView(va);
                    bottomSheetDialog.show();
                } else {
                    Toast.makeText(uploadved.this, "من فضلك قم باختيار فيديو", Toast.LENGTH_SHORT).show();
                }
            }

        });
    }////////////////////////////////////////////////////

    // This method converts the video.

    ///////////////////////////////////////////////////
    private void selectVideo() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("video/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(
                Intent.createChooser(intent, "Select Video"),
                SELECT_VIDEO_REQUEST);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(
                requestCode, permissions, grantResults);
        // check condition
        if (requestCode == 1 && grantResults.length > 0
                && grantResults[0]
                == PackageManager.PERMISSION_GRANTED) {
            selectVideo();
        } else {
            Toast.makeText(getApplicationContext(), "Permission Denied !", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode,
                data);
        if (requestCode == 100 && resultCode == RESULT_OK && data != null) {
            videoUri = data.getData();
            displayName = String.valueOf(Calendar.getInstance().getTimeInMillis() + ".mp4");
            MediaPlayer mp = MediaPlayer.create(this, videoUri);
            videoUri = data.getData();
            String videoPath = videoUri.getPath();
            Log.e("tyyyyy", videoPath);
            int duration = mp.getDuration();
            mp.release();
            String durationStr = String.format("%d", TimeUnit.MILLISECONDS.toSeconds(duration) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration)));
            String durationStr2 = String.format("%d", TimeUnit.MILLISECONDS.toMinutes(duration));


            outputPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + "compressed_video.mp4";
           width = 576;
           height = 1024;
           file=new File(videoUri.getPath());
            String filePath = file.getAbsolutePath().toString();
            inputPath=videoUri;
            Path=filePath;
            vedgetr.setVideoURI(videoUri);
            vedgetr.start();
            Log.d("tyyyyy",filePath);
         /*   try {
                resizeVideo(inputPath, outputPath, width, height);
                //vedgetr.setVideoPath(outputPath);
               // vedgetr.start();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }*/
            /*String outputPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + "compressed_video.mp4";
            String path = videoUri.getPath().toString();
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            retriever.setDataSource(this,videoUri);

            String height = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
            Log.e("tyyyyy", "h"+height);
            String width = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
            Log.e("tyyyyy", "w"+width);
            int w = Integer.parseInt(width);
            int h = Integer.parseInt(height);

            int quality = w*h/1024 * 1024/1000;

            String qul= String.valueOf(quality);
            Log.e("tyyyyy", qul);
            // Display the video quality

            Log.e("tyyyyy", outputPath);
            file =new File(Path);
            String inputpath=file.getPath().toString();
            String filePath = file.getAbsolutePath().toString();
            Log.e("tyyyyy", filePath);*/
            try {
                convert2();
            } catch (IOException e) {
                throw new RuntimeException(e);

            }
        }

    }

    public void convert2() throws IOException {
        dila = ProgressDialog.show(uploadved.this, "برجاء الانتظار", "جاري تجهيز الفيديو");



            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            retriever.setDataSource(uploadved.this,videoUri);
            String height = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
            Log.e("tyyyyy", "h" + height);
            String width = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
            Log.e("tyyyyy", "w" + width);
            w = Integer.parseInt(width);
            h = Integer.parseInt(height);

            int quality = w * h / 1024 * 1024 / 1000;
            qul = String.valueOf(quality);
            Log.e("tyyyyy", qul);
            retriever.release();
            if (h > 1024) {
                try {
                    File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), displayName + ".mp4");
                    file.createNewFile();
                    String outputPath = file.getPath().toString();
                    Log.d("tyyyyy", "outpath is " + outputPath);

                    retriever.setDataSource(uploadved.this,videoUri);
                    Bitmap bmp = retriever.getFrameAtTime();
                    int newWidth = 576;
                    int newHeight = 1024;
                    Bitmap resizedBmp = Bitmap.createScaledBitmap(bmp, newWidth, newHeight, true);
                    retriever.release();

                    // Save the video to the phone
                    MediaMuxer muxer = new MediaMuxer(outputPath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);

// Add the video track
                    int videoTrackIndex = muxer.addTrack(MediaFormat.createVideoFormat(outputPath, newWidth, newHeight));
                    String aduo = String.valueOf(videoTrackIndex);
                    Log.e("tyyyyy", "videoResolution" + "=" + aduo);

// Add the audio track
                    int audioTrackIndex = muxer.addTrack(MediaFormat.createAudioFormat(outputPath, 44100, 2));
                    String adad = String.valueOf(audioTrackIndex);
                    Log.e("tyyyyy", "videoResolution" + "=" + adad);

// Start writing to the muxer
                    muxer.start();

// Write the video frames to the muxer
                    ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 1024);
                    int[] pixels = new int[resizedBmp.getWidth() * resizedBmp.getHeight()];

                    for (int i = 0; i < resizedBmp.getHeight(); i++) {
                        buffer.clear();
                        resizedBmp.getPixels(pixels, 0, resizedBmp.getWidth(), 0, i, resizedBmp.getWidth(), resizedBmp.getHeight());
                        byte[] bytes = new byte[buffer.limit()];
                        for (int j = 0; j < bytes.length; j++) {
                            bytes[j] = buffer.get(j);
                        }

                        MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
                        info.offset = 0;
                        info.size = bytes.length;

                        muxer.writeSampleData(videoTrackIndex, buffer, info);
                    }

// Write the audio samples to the muxer
                    short[] samples = new short[resizedBmp.getWidth() * resizedBmp.getHeight()];
                    int[] intSamples = new int[samples.length];

                    for (int i = 0; i < resizedBmp.getHeight(); i++) {
                        buffer.clear();
                        resizedBmp.getPixels(intSamples, 0, resizedBmp.getWidth(), 0, i, resizedBmp.getWidth(), resizedBmp.getHeight());
                        for (int j = 0; j < samples.length; j++) {
                            buffer.putShort((short) intSamples[j]);
                        }
                        byte[] bytes = buffer.array();
                        MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
                        info.offset = 0;
                        info.size = bytes.length;

                        muxer.writeSampleData(audioTrackIndex, buffer, info);
                    }

// Stop writing to the muxer
                    muxer.stop();
                    muxer.release();
                    uritoupload = Uri.parse(outputPath);
                    vedgetr.setMediaController(new MediaController(this));
                    dila.dismiss();
                    vedgetr.setVideoURI(uritoupload);
                    vedgetr.start();
                } catch (IOException e) {
                    Log.e("tyyyyy", "catch" + e.getMessage().toString());
                }
            } else if (w > 576) {
                try {


                    Bitmap bmp = retriever.getFrameAtTime();
                    int newWidth = 576;
                    int newHeight = 1024;
                    Bitmap resizedBmp = Bitmap.createScaledBitmap(bmp, newWidth, newHeight, true);
                    retriever.release();
                    File newVideoFile = new File(Environment.getExternalStorageDirectory(), "new_video.mp4");

                    // Save the video to the phone
                    MediaMuxer muxer = new MediaMuxer(newVideoFile.getPath(), MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);

                    // Add the video track
                    int videoTrackIndex = muxer.addTrack(MediaFormat.createVideoFormat(newVideoFile.getPath(), newWidth, newHeight));
                    String aduo = String.valueOf(videoTrackIndex);
                    Log.e("tyyyyy", "videoResolution" + "=" + aduo);
                    // Add the audio track
                    int audioTrackIndex = muxer.addTrack(MediaFormat.createAudioFormat(newVideoFile.getPath(), 44100, 2));
                    String adad = String.valueOf(videoTrackIndex);
                    Log.e("tyyyyy", "videoResolution" + "=" + adad);
                    // Start writing to the muxer
                    muxer.start();

                    // Write the video frames to the muxer
                    ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 1024);
                    int[] pixels = new int[resizedBmp.getWidth() * resizedBmp.getHeight()];

                    for (int i = 0; i < resizedBmp.getHeight(); i++) {
                        buffer.clear();
                        resizedBmp.getPixels(pixels, 0, resizedBmp.getWidth(), 0, i, resizedBmp.getWidth(), resizedBmp.getHeight());
                        byte[] bytes = new byte[buffer.limit()];
                        for (int j = 0; j < bytes.length; j++) {
                            bytes[j] = buffer.get(j);
                        }

                        MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
                        info.offset = 0;
                        info.size = bytes.length;

                        muxer.writeSampleData(videoTrackIndex, buffer, info);
                    }

                    // Write the audio samples to the muxer
                    short[] samples = new short[resizedBmp.getWidth() * resizedBmp.getHeight()];
                    int[] intSamples = new int[samples.length];

                    for (int i = 0; i < resizedBmp.getHeight(); i++) {
                        buffer.clear();
                        resizedBmp.getPixels(intSamples, 0, resizedBmp.getWidth(), 0, i, resizedBmp.getWidth(), resizedBmp.getHeight());
                        for (int j = 0; j < samples.length; j++) {
                            buffer.putShort((short) intSamples[j]);
                        }
                        byte[] bytes = buffer.array();
                        MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
                        info.offset = 0;
                        info.size = bytes.length;

                        muxer.writeSampleData(audioTrackIndex, buffer, info);
                    }

                    // Stop writing to the muxer
                    muxer.stop();
                    muxer.release();
                    uritoupload = Uri.parse(newVideoFile.getPath());

                    vedgetr.setMediaController(new MediaController(this));
                    dila.dismiss();
                    vedgetr.setVideoURI(uritoupload);
                    vedgetr.start();
                } catch (IOException e) {
                    Log.e("tyyyyy", "catch" + e.toString());
                }
            } else {
                vedgetr.setMediaController(new MediaController(this));
                dila.dismiss();
                vedgetr.start();
            }
        }

 

Recommended Posts

لا توجد أي إجابات على هذا السؤال بعد

انضم إلى النقاش

يمكنك أن تنشر الآن وتسجل لاحقًا. إذا كان لديك حساب، فسجل الدخول الآن لتنشر باسم حسابك.

زائر
أجب على هذا السؤال...

×   لقد أضفت محتوى بخط أو تنسيق مختلف.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   جرى استعادة المحتوى السابق..   امسح المحرر

×   You cannot paste images directly. Upload or insert images from URL.

  • إعلانات

  • تابعنا على



×
×
  • أضف...