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

السؤال

نشر
package com.tocrest.a2crest.vedio;


import android.Manifest;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.media.MediaCodec;
import android.media.MediaFormat;
import android.media.MediaMetadataRetriever;
import android.media.MediaMuxer;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.makeramen.roundedimageview.RoundedImageView;
import com.tocrest.a2crest.Dialog.difroved;
import com.tocrest.a2crest.R;
import com.tocrest.a2crest.shall;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;



@SuppressWarnings("ALL")
public class uploadved extends AppCompatActivity implements difroved.ExampleDialogeListener {
    TextView uploader;
    RoundedImageView geter;
    VideoView vedgetr;
    MediaController mc;
    File file;
    String wasfst;
    String realPath;
    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;
    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;
    private static final int REQUEST_FOR_VIDEO_FILE = 1000;
    private TextView tv_input, tv_output, tv_indicator, tv_progress;
    private String outputDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();

    private String inputPath2;

    private ProgressBar pb_compress;

    private long startTime, endTime;

    @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);
                }
            }
        });
        
    private void selectVideo() {
        Intent intent = new Intent(Intent.ACTION_PICK,MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
        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 == SELECT_VIDEO_REQUEST && resultCode == RESULT_OK && data != null) {
            videoUri = data.getData();
            displayName = String.valueOf(Calendar.getInstance().getTimeInMillis());
            MediaPlayer mp = MediaPlayer.create(this, videoUri);
            Log.e("tyyyyy", "viduritost"+"="+videoUri.toString());
            Log.e("tyyyyy", "viduripathtost"+"="+videoUri.getPath().toString());
            file=new File(videoUri.getPath());
             realPath =data.getDataString();
         
            Log.e("tyyyyy", "videopath"+realPath);
            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));
            try {
                convert3();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            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;
         
            Log.d("tyyyyy","PATH URI IS ="+videoUri.getPath().toString());
        
        }


    }



  
    public void convert3() 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);
        String width = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
        int w = Integer.parseInt(width);
        int h = Integer.parseInt(height);

        int quality = w*h/1024*1024;
        String qul = String.valueOf(quality);
        Log.e("tyyyyy", "videoResolution = " + qul);
        Log.e("tyyyyy", "hi = " +height);
        Log.e("tyyyyy", "wi = " +width);
        retriever.release();

        if (h > 1024) {
            try {
                File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), displayName + ".mp4");
                String outputPath = file.getPath();
                String rettopatha=videoUri.getPath().toString();
                Log.d("tyyyyy","rettopath"+"="+rettopatha);
                Bitmap bmp = retriever.getFrameAtTime();
                int newWidth = 576;
                int newHeight = 1024;
                Bitmap resizedBmp = Bitmap.createScaledBitmap(bmp, newWidth, newHeight, true);
                retriever.release();

                MediaMuxer muxer = new MediaMuxer(outputPath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);

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

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

                muxer.start();

                // Write the video frames to the muxer
                ByteBuffer buffer = ByteBuffer.allocateDirect(resizedBmp.getByteCount());
                resizedBmp.copyPixelsToBuffer(buffer);
                buffer.flip();

                MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
                info.flags = MediaCodec.BUFFER_FLAG_KEY_FRAME;
                info.offset = 0;

                muxer.writeSampleData(videoTrackIndex, buffer, info);

                // Write the audio samples to the muxer
                short[] samples = new short[resizedBmp.getWidth() * resizedBmp.getHeight()];
                buffer.clear();
                buffer.asShortBuffer().put(samples);
                buffer.flip();

                info = new MediaCodec.BufferInfo();
                info.offset = 0;
                info.size = buffer.remaining();

                muxer.writeSampleData(audioTrackIndex, buffer, info);

                muxer.stop();
                muxer.release();

                Uri 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());
            }
        }
       else if (w > 576) {
            try {
                File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), displayName + ".mp4");
                String outputPath = file.getPath();
                File filea=new File(videoUri.getPath());
                retriever.setDataSource(outputPath);
                Bitmap bmp = retriever.getFrameAtTime();
                int newWidth = 576;
                int newHeight = 1024;
                Bitmap resizedBmp = Bitmap.createScaledBitmap(bmp, newWidth, newHeight, true);
                retriever.release();

                MediaMuxer muxer = new MediaMuxer(outputPath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);

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

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

                muxer.start();

                // Write the video frames to the muxer
                ByteBuffer buffer = ByteBuffer.allocateDirect(resizedBmp.getByteCount());
                resizedBmp.copyPixelsToBuffer(buffer);
                buffer.flip();

                MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
                info.flags = MediaCodec.BUFFER_FLAG_KEY_FRAME;
                info.offset = 0;

                muxer.writeSampleData(videoTrackIndex, buffer, info);

                // Write the audio samples to the muxer
                short[] samples = new short[resizedBmp.getWidth() * resizedBmp.getHeight()];
                buffer.clear();
                buffer.asShortBuffer().put(samples);
                buffer.flip();

                info = new MediaCodec.BufferInfo();
                info.offset = 0;
                info.size = buffer.remaining();

                muxer.writeSampleData(audioTrackIndex, buffer, info);

                muxer.stop();
                muxer.release();

                Uri 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());
            }
        }
       else {
           dila.dismiss();
           vedgetr.setVideoURI(videoUri);
           vedgetr.start();
            Toast.makeText(this, "try", Toast.LENGTH_SHORT).show();
        }
    }


}

 

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.

  • إعلانات

  • تابعنا على



×
×
  • أضف...