Android 仿微信朋友圈拍小視頻上傳到服務器


這個接上一個寫的實現拍小視頻和傳到服務器的 
這里寫圖片描述這里寫圖片描述這里寫圖片描述

界面是這個樣子滴.

我也知不知道怎么給圖片搞小一點o(╯□╰)o

布局文件是這樣的【認真臉】

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#2B2B2B"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/ll_historydatadetail_title"
        android:layout_width="match_parent"
        android:layout_height="51dp"
        android:background="@color/titlecolor"
        android:orientation="horizontal">

        <ImageButton
            android:id="@+id/imb_back"
            android:layout_width="50dp"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:layout_marginLeft="5dp"
            android:background="@null"
            android:src="@mipmap/upload_video_esc" />

    </LinearLayout>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <cn.com.jwtimes.www.jwtimes.view.MovieRecorderView
            android:id="@+id/movieRecorderView"
            android:layout_width="match_parent"
            android:layout_height="0dp" />

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:id="@+id/textView_release_to_cancel"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_centerHorizontal="true"
                android:layout_marginBottom="50dp"
                android:background="#99b31921"
                android:padding="2dp"
                android:text="松開取消"
                android:textColor="#ffffff"
                android:visibility="gone" />
        </RelativeLayout>
    </FrameLayout>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/datadetailtext">

        <RelativeLayout
            android:id="@+id/rl_bottom_root"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/textView_up_to_cancel"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="20dp"
                android:background="#33000000"
                android:text="上移取消"
                android:textColor="#ffffff"
                android:visibility="gone" />

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_marginRight="15dp"
                android:layout_marginTop="15dp"
                android:orientation="horizontal">

                <TextView
                    android:id="@+id/textView_count_down"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textColor="#707070"
                    android:textSize="14sp" />
            </LinearLayout>

            <ProgressBar
                android:id="@+id/progressBar_loading"
                style="@android:style/Widget.ProgressBar.Horizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:minHeight="5dp" />

            <Button
                android:id="@+id/shoot_button"
                android:layout_width="150dp"
                android:layout_height="150dp"
                android:layout_below="@+id/progressBar_loading"
                android:layout_centerHorizontal="true"
                android:layout_gravity="center"
                android:layout_marginTop="40dp"
                android:background="@drawable/voidbutton"
                android:text="按住拍"
                android:textColor="#fff" />
        </RelativeLayout>
    </FrameLayout>
</LinearLayout>

中間發現一個特務就是混進來的自定義錄制視頻的的MovieRecorderView這個家伙

package cn.com.jwtimes.www.jwtimes.view;


import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.media.MediaRecorder;
import android.media.MediaRecorder.AudioEncoder;
import android.media.MediaRecorder.AudioSource;
import android.media.MediaRecorder.OnErrorListener;
import android.media.MediaRecorder.OutputFormat;
import android.media.MediaRecorder.VideoEncoder;
import android.media.MediaRecorder.VideoSource;
import android.os.Build;
import android.os.Environment;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.widget.LinearLayout;

import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cn.com.jwtimes.www.jwtimes.R;


/**
 * Created by 王超然 on 2016/6/3.
 */
public class MovieRecorderView extends LinearLayout implements OnErrorListener {
    private static final String LOG_TAG = "MovieRecorderView";

    private Context context;

    private SurfaceView surfaceView;
    private SurfaceHolder surfaceHolder;

    private MediaRecorder mediaRecorder;
    private Camera camera;
    private Timer timer;//計時器

    private int mWidth;//視頻錄制分辨率寬度
    private int mHeight;//視頻錄制分辨率高度
    private boolean isOpenCamera;//是否一開始就打開攝像頭
    private int recordMaxTime;//最長拍攝時間
    private int timeCount;//時間計數
    private File recordFile = null;//視頻文件
    private long sizePicture = 0;

    public MovieRecorderView(Context context) {
        this(context, null);
    }

    public MovieRecorderView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public MovieRecorderView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MovieRecorderView, defStyle, 0);
        mWidth = a.getInteger(R.styleable.MovieRecorderView_record_width, 640);//默認640
        mHeight = a.getInteger(R.styleable.MovieRecorderView_record_height, 360);//默認360

        isOpenCamera = a.getBoolean(R.styleable.MovieRecorderView_is_open_camera, true);//默認打開攝像頭
        recordMaxTime = a.getInteger(R.styleable.MovieRecorderView_record_max_time, 10);//默認最大拍攝時間為10s

        LayoutInflater.from(context).inflate(R.layout.movie_recorder_view, this);
        surfaceView = (SurfaceView) findViewById(R.id.surfaceview);
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(new CustomCallBack());
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        a.recycle();
    }

    /**
     * SurfaceHolder回調
     */
    private class CustomCallBack implements Callback {
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            if (!isOpenCamera)
                return;
            try {
                initCamera();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            if (!isOpenCamera)
                return;
            freeCameraResource();
        }
    }

    /**
     * 初始化攝像頭
     */
    public void initCamera() throws IOException {
        if (camera != null) {
            freeCameraResource();
        }
        try {
            if (checkCameraFacing(Camera.CameraInfo.CAMERA_FACING_BACK)) {
                camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
            } else if (checkCameraFacing(Camera.CameraInfo.CAMERA_FACING_FRONT)) {
                camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
            }
        } catch (Exception e) {
            e.printStackTrace();
            freeCameraResource();
            ((Activity) context).finish();
        }
        if (camera == null)
            return;

        setCameraParams();
        camera.setDisplayOrientation(90);
        camera.setPreviewDisplay(surfaceHolder);
        camera.startPreview();
        camera.unlock();
    }

    /**
     * 檢查是否有攝像頭
     *
     * @param facing 前置還是后置
     * @return
     */
    private boolean checkCameraFacing(int facing) {
        int cameraCount = Camera.getNumberOfCameras();
        Camera.CameraInfo info = new Camera.CameraInfo();
        for (int i = 0; i < cameraCount; i++) {
            Camera.getCameraInfo(i, info);
            if (facing == info.facing) {
                return true;
            }
        }
        return false;
    }

    /**
     * 設置攝像頭為豎屏
     */
    private void setCameraParams() {
        if (camera != null) {
            Parameters params = camera.getParameters();
            params.set("orientation", "portrait");
            List<Camera.Size> supportedPictureSizes = params.getSupportedPictureSizes();
            for (Camera.Size size : supportedPictureSizes) {
                sizePicture = (size.height * size.width) > sizePicture ? size.height * size.width : sizePicture;
            }
//            LogUtil.e(LOG_TAG,"手機支持的最大像素supportedPictureSizes===="+sizePicture);
            setPreviewSize(params);
            camera.setParameters(params);
        }
    }

    /**
     * 根據手機支持的視頻分辨率,設置預覽尺寸
     *
     * @param params
     */
    private void setPreviewSize(Parameters params) {
        if (camera == null) {
            return;
        }
        //獲取手機支持的分辨率集合,並以寬度為基准降序排序
        List<Camera.Size> previewSizes = params.getSupportedPreviewSizes();
        Collections.sort(previewSizes, new Comparator<Camera.Size>() {
            @Override
            public int compare(Camera.Size lhs, Camera.Size rhs) {
                if (lhs.width > rhs.width) {
                    return -1;
                } else if (lhs.width == rhs.width) {
                    return 0;
                } else {
                    return 1;
                }
            }
        });

        float tmp = 0f;
        float minDiff = 100f;
        float ratio = 3.0f / 4.0f;//TODO 高寬比率3:4,且最接近屏幕寬度的分辨率,可以自己選擇合適的想要的分辨率
        Camera.Size best = null;
        for (Camera.Size s : previewSizes) {
            tmp = Math.abs(((float) s.height / (float) s.width) - ratio);
            Log.e(LOG_TAG, "setPreviewSize: width:" + s.width + "...height:" + s.height);
//            LogUtil.e(LOG_TAG,"tmp:" + tmp);
            if (tmp < minDiff) {
                minDiff = tmp;
                best = s;
            }
        }


        params.setPreviewSize(best.width, best.height);//預覽比率

        Log.e(LOG_TAG, "setPreviewSize BestSize: width:" + best.width + "...height:" + best.height);

        //TODO 大部分手機支持的預覽尺寸和錄制尺寸是一樣的,也有特例,有些手機獲取不到,那就把設置錄制尺寸放到設置預覽的方法里面
        if (params.getSupportedVideoSizes() == null || params.getSupportedVideoSizes().size() == 0) {
            mWidth = best.width;
            mHeight = best.height;
        } else {
            setVideoSize(params);
        }
    }

    /**
     * 根據手機支持的視頻分辨率,設置錄制尺寸
     *
     * @param params
     */
    private void setVideoSize(Parameters params) {
        if (camera == null) {
            return;
        }
        //獲取手機支持的分辨率集合,並以寬度為基准降序排序
        List<Camera.Size> previewSizes = params.getSupportedVideoSizes();
        Collections.sort(previewSizes, new Comparator<Camera.Size>() {
            @Override
            public int compare(Camera.Size lhs, Camera.Size rhs) {
                if (lhs.width > rhs.width) {
                    return -1;
                } else if (lhs.width == rhs.width) {
                    return 0;
                } else {
                    return 1;
                }
            }
        });

        float tmp = 0f;
        float minDiff = 100f;
        float ratio = 3.0f / 4.0f;//高寬比率3:4,且最接近屏幕寬度的分辨率
        Camera.Size best = null;
        for (Camera.Size s : previewSizes) {
            tmp = Math.abs(((float) s.height / (float) s.width) - ratio);
            Log.e(LOG_TAG, "setVideoSize: width:" + s.width + "...height:" + s.height);
            if (tmp < minDiff) {
                minDiff = tmp;
                best = s;
            }
        }
        Log.e(LOG_TAG, "setVideoSize BestSize: width:" + best.width + "...height:" + best.height);
        //設置錄制尺寸
        mWidth = best.width;
        mHeight = best.height;
    }

    /**
     * 釋放攝像頭資源
     */
    private void freeCameraResource() {
        try {
            if (camera != null) {
                camera.setPreviewCallback(null);
                camera.stopPreview();
                camera.lock();
                camera.release();
                camera = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            camera = null;
        }
    }

    /**
     * 創建視頻文件
     */
    private void createRecordDir() {
        File sampleDir = new File(Environment.getExternalStorageDirectory() + File.separator + "SampleVideo/video/");
        if (!sampleDir.exists()) {
            sampleDir.mkdirs();
        }
        try {
            //TODO 文件名用的時間戳,可根據需要自己設置,格式也可以選擇3gp,在初始化設置里也需要修改
            recordFile = new File(sampleDir, System.currentTimeMillis() + ".mp4");
//            recordFile = new File(sampleDir, System.currentTimeMillis() + ".mp4");
//            File.createTempFile(AccountInfo.userId, ".mp4", sampleDir);
//            LogUtil.e(LOG_TAG, recordFile.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 錄制視頻初始化
     */
    private void initRecord() throws Exception {
        mediaRecorder = new MediaRecorder();
        mediaRecorder.reset();
        if (camera != null)
            mediaRecorder.setCamera(camera);
        mediaRecorder.setOnErrorListener(this);
        mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
        mediaRecorder.setVideoSource(VideoSource.CAMERA);//視頻源
        mediaRecorder.setAudioSource(AudioSource.MIC);//音頻源
        mediaRecorder.setOutputFormat(OutputFormat.MPEG_4);//TODO 視頻輸出格式 也可設為3gp等其他格式
        mediaRecorder.setAudioEncoder(AudioEncoder.AMR_NB);//音頻格式
        mediaRecorder.setVideoSize(mWidth, mHeight);//設置分辨率
//        mediaRecorder.setVideoFrameRate(25);//TODO 設置每秒幀數 這個設置有可能會出問題,有的手機不支持這種幀率就會錄制失敗,這里使用默認的幀率,當然視頻的大小肯定會受影響
//        LogUtil.e(LOG_TAG,"手機支持的最大像素supportedPictureSizes===="+sizePicture);
        if (sizePicture < 3000000) {//這里設置可以調整清晰度
            mediaRecorder.setVideoEncodingBitRate(3 * 1024 * 512);
        } else if (sizePicture <= 5000000) {
            mediaRecorder.setVideoEncodingBitRate(2 * 1024 * 512);
        } else {
            mediaRecorder.setVideoEncodingBitRate(1 * 1024 * 512);
        }
        mediaRecorder.setOrientationHint(90);//輸出旋轉90度,保持豎屏錄制

        mediaRecorder.setVideoEncoder(VideoEncoder.H264);//視頻錄制格式
        //mediaRecorder.setMaxDuration(Constant.MAXVEDIOTIME * 1000);
        mediaRecorder.setOutputFile(recordFile.getAbsolutePath());
        mediaRecorder.prepare();
        mediaRecorder.start();
    }

    /**
     * 開始錄制視頻
     *
     * @param onRecordFinishListener 達到指定時間之后回調接口
     */
    public void record(final OnRecordFinishListener onRecordFinishListener) {
        this.onRecordFinishListener = onRecordFinishListener;
        createRecordDir();
        try {
            //如果未打開攝像頭,則打開
            if (!isOpenCamera)
                initCamera();
            initRecord();
            timeCount = 0;//時間計數器重新賦值
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    timeCount++;
                    //progressBar.setProgress(timeCount);//設置進度條
                    if (onRecordProgressListener != null) {
                        onRecordProgressListener.onProgressChanged(recordMaxTime, timeCount);
                    }

                    //達到指定時間,停止拍攝
                    if (timeCount == recordMaxTime) {
                        stop();
                        if (MovieRecorderView.this.onRecordFinishListener != null)
                            MovieRecorderView.this.onRecordFinishListener.onRecordFinish();
                    }
                }
            }, 0, 1000);
        } catch (Exception e) {
            e.printStackTrace();
            if (mediaRecorder != null) {
                mediaRecorder.release();
            }
            freeCameraResource();
        }
    }

    /**
     * 停止拍攝
     */
    public void stop() {
        stopRecord();
        releaseRecord();
        freeCameraResource();
    }

    /**
     * 停止錄制
     */
    public void stopRecord() {
        //progressBar.setProgress(0);
        if (timer != null)
            timer.cancel();
        if (mediaRecorder != null) {
            mediaRecorder.setOnErrorListener(null);//設置后防止崩潰
            mediaRecorder.setPreviewDisplay(null);
            try {
                mediaRecorder.stop();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 釋放資源
     */
    private void releaseRecord() {
        if (mediaRecorder != null) {
            mediaRecorder.setOnErrorListener(null);
            try {
                mediaRecorder.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        mediaRecorder = null;
    }

    /**
     * 獲取當前錄像時間
     *
     * @return timeCount
     */
    public int getTimeCount() {
        return timeCount;
    }

    /**
     * 設置最大錄像時間
     *
     * @param recordMaxTime
     */
    public void setRecordMaxTime(int recordMaxTime) {
        this.recordMaxTime = recordMaxTime;
    }

    /**
     * 返回錄像文件
     *
     * @return recordFile
     */
    public File getRecordFile() {
        return recordFile;
    }

    /**
     * 錄制完成監聽
     */
    private OnRecordFinishListener onRecordFinishListener;

    /**
     * 錄制完成接口
     */
    public interface OnRecordFinishListener {
        void onRecordFinish();
    }

    /**
     * 錄制進度監聽
     */
    private OnRecordProgressListener onRecordProgressListener;

    /**
     * 設置錄制進度監聽
     *
     * @param onRecordProgressListener
     */
    public void setOnRecordProgressListener(OnRecordProgressListener onRecordProgressListener) {
        this.onRecordProgressListener = onRecordProgressListener;
    }

    /**
     * 錄制進度接口
     */
    public interface OnRecordProgressListener {
        /**
         * 進度變化
         *
         * @param maxTime     最大時間,單位秒
         * @param currentTime 當前進度
         */
        void onProgressChanged(int maxTime, int currentTime);
    }

    @Override
    public void onError(MediaRecorder mr, int what, int extra) {
        try {
            if (mr != null)
                mr.reset();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

這個是抄的,感謝那個偉大的程序員,我踩在了巨人的肩膀上。 
button的樣式:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <solid android:color="#000"/>
    <stroke android:width="1dp" android:color="#a0a0a0"/>

    <corners  android:topLeftRadius="100dp"
        android:topRightRadius="100dp"
        android:bottomRightRadius="100dp"
        android:bottomLeftRadius="100dp"
        />

</shape>

然后是Activity:

package cn.com.jwtimes.www.jwtimes.ui.disaupload;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;

import cn.com.jwtimes.www.jwtimes.R;
import cn.com.jwtimes.www.jwtimes.view.MovieRecorderView;


public class MovieRecorderActivity extends AppCompatActivity {
    private static final String LOG_TAG = "RecordVideoActivity";
    private static final int REQ_CODE = 110;
    private static final int RES_CODE = 111;
    /**
     * 錄制進度
     */
    private static final int RECORD_PROGRESS = 100;
    /**
     * 錄制結束
     */
    private static final int RECORD_FINISH = 101;

    private MovieRecorderView movieRecorderView;
    private Button buttonShoot;
    private RelativeLayout rlBottomRoot;
    private ProgressBar progressVideo;
    private TextView textViewCountDown;
    private TextView textViewUpToCancel;//上移取消
    private TextView textViewReleaseToCancel;//釋放取消
    /**
     * 是否結束錄制
     */
    private boolean isFinish = true;
    /**
     * 是否觸摸在松開取消的狀態
     */
    private boolean isTouchOnUpToCancel = false;
    /**
     * 當前進度
     */
    private int currentTime = 0;
    private ImageButton imb_back;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RECORD_PROGRESS:
                    progressVideo.setProgress(currentTime);
                    if (currentTime < 10) {
                        textViewCountDown.setText("00:0" + currentTime);
                    } else {
                        textViewCountDown.setText("00:" + currentTime);
                    }
                    break;
                case RECORD_FINISH:
                    if (isTouchOnUpToCancel) {//錄制結束,還在上移刪除狀態沒有松手,就復位錄制
                        resetData();
                    } else {//錄制結束,在正常位置,錄制完成跳轉頁面
                        isFinish = true;
                        buttonShoot.setEnabled(false);
                        finishActivity();
                    }
                    break;
            }
        }
    };
    /**
     * 按下的位置
     */
    private float startY;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_movie_recorder);
        initView();


    }

    private void initView() {

        imb_back = (ImageButton) findViewById(R.id.imb_back);
        imb_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MovieRecorderActivity.this.finish();
                overridePendingTransition(R.anim.anim_slide_left_in, R.anim.anim_slide_right_out);
            }
        });

        movieRecorderView = (MovieRecorderView) findViewById(R.id.movieRecorderView);
        buttonShoot = (Button) findViewById(R.id.shoot_button);
        rlBottomRoot = (RelativeLayout) findViewById(R.id.rl_bottom_root);
        //progressVideo = (DonutProgress) findViewById(R.id.progress_video);
        progressVideo = (ProgressBar) findViewById(R.id.progressBar_loading);
        textViewCountDown = (TextView) findViewById(R.id.textView_count_down);
        textViewCountDown.setText("00:00");
        textViewUpToCancel = (TextView) findViewById(R.id.textView_up_to_cancel);
        textViewReleaseToCancel = (TextView) findViewById(R.id.textView_release_to_cancel);

        DisplayMetrics dm = getApplicationContext().getResources().getDisplayMetrics();
        int width = dm.widthPixels;
        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) movieRecorderView.getLayoutParams();
        layoutParams.height = width * 4 / 3;//根據屏幕寬度設置預覽控件的尺寸,為了解決預覽拉伸問題
        //LogUtil.e(LOG_TAG, "mSurfaceViewWidth:" + width + "...mSurfaceViewHeight:" + layoutParams.height);
        movieRecorderView.setLayoutParams(layoutParams);

        FrameLayout.LayoutParams rlBottomRootLayoutParams = (FrameLayout.LayoutParams) rlBottomRoot.getLayoutParams();
        rlBottomRootLayoutParams.height = width / 3 * 2;
        rlBottomRoot.setLayoutParams(rlBottomRootLayoutParams);

        //處理觸摸事件
        buttonShoot.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    textViewUpToCancel.setVisibility(View.VISIBLE);//提示上移取消

                    isFinish = false;//開始錄制
                    startY = event.getY();//記錄按下的坐標
                    movieRecorderView.record(new MovieRecorderView.OnRecordFinishListener() {
                        @Override
                        public void onRecordFinish() {
                            handler.sendEmptyMessage(RECORD_FINISH);
                        }
                    });
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    textViewUpToCancel.setVisibility(View.GONE);
                    textViewReleaseToCancel.setVisibility(View.GONE);

                    if (startY - event.getY() > 100) {//上移超過一定距離取消錄制,刪除文件
                        if (!isFinish) {
                            resetData();
                        }
                    } else {
                        if (movieRecorderView.getTimeCount() > 3) {//錄制時間超過三秒,錄制完成
                            handler.sendEmptyMessage(RECORD_FINISH);
                        } else {//時間不足取消錄制,刪除文件
                            Toast.makeText(MovieRecorderActivity.this, "視頻錄制時間太短", Toast.LENGTH_SHORT).show();
                            resetData();
                        }
                    }
                } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
                    //根據觸摸上移狀態切換提示
                    if (startY - event.getY() > 100) {
                        isTouchOnUpToCancel = true;//觸摸在松開就取消的位置
                        if (textViewUpToCancel.getVisibility() == View.VISIBLE) {
                            textViewUpToCancel.setVisibility(View.GONE);
                            textViewReleaseToCancel.setVisibility(View.VISIBLE);
                        }
                    } else {
                        isTouchOnUpToCancel = false;//觸摸在正常錄制的位置
                        if (textViewUpToCancel.getVisibility() == View.GONE) {
                            textViewUpToCancel.setVisibility(View.VISIBLE);
                            textViewReleaseToCancel.setVisibility(View.GONE);
                        }
                    }
                } else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
                    resetData();
                }
                return true;
            }
        });

        progressVideo.setMax(10);
        movieRecorderView.setOnRecordProgressListener(new MovieRecorderView.OnRecordProgressListener() {
            @Override
            public void onProgressChanged(int maxTime, int currentTime) {
                MovieRecorderActivity.this.currentTime = currentTime;
                handler.sendEmptyMessage(RECORD_PROGRESS);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        checkCameraPermission();
    }

    /**
     * 檢測攝像頭和錄音權限
     */
    private void checkCameraPermission() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            // Camera permission has not been granted.
            Toast.makeText(this, "視頻錄制和錄音沒有授權", Toast.LENGTH_LONG);
            this.finish();
        } else {
            resetData();
        }
    }

    /**
     * 重置狀態
     */
    private void resetData() {
        if (movieRecorderView.getRecordFile() != null)
            movieRecorderView.getRecordFile().delete();
        movieRecorderView.stop();
        isFinish = true;
        currentTime = 0;
        progressVideo.setProgress(0);

        buttonShoot.setEnabled(true);
        textViewUpToCancel.setVisibility(View.GONE);
        textViewReleaseToCancel.setVisibility(View.GONE);
        try {
            movieRecorderView.initCamera();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        isFinish = true;
        movieRecorderView.stop();
    }

    /**
     * 遞歸刪除目錄下的所有文件及子目錄下所有文件
     *
     * @param dir 將要刪除的文件目錄
     * @return
     */
    private boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //遞歸刪除目錄中的子目錄下
            for (int i = 0; i < children.length; i++) {
                if (!deleteDir(new File(dir, children[i]))) {
                    return false;
                }
            }
        }
        return dir.delete();
    }

//    @Override
//    public void onDestroy() {
//        //TODO 退出界面刪除文件,如果要刪除文件夾,需要提供文件夾路徑
//        if (movieRecorderView.getRecordFile() != null) {
//            File file = new File(movieRecorderView.getRecordFile().getAbsolutePath());
//            if (file != null && file.exists()) {
//                Log.e(LOG_TAG, "file.exists():" + file.exists());
//                file.delete();
//            }
//        }
//        super.onDestroy();
//    }
    //視頻錄制結束后,跳轉的函數
    private void finishActivity() {
        if (isFinish) {
            movieRecorderView.stop();
            Intent intent = new Intent(this, SendMovieActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("text", movieRecorderView.getRecordFile().getAbsolutePath());
            intent.putExtras(bundle);
            startActivity(intent);
            Toast.makeText(MovieRecorderActivity.this, "錄制結束", Toast.LENGTH_SHORT);
            MovieRecorderActivity.this.finish();
            overridePendingTransition(R.anim.anim_slide_right_in, R.anim.anim_slide_left_out);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQ_CODE && resultCode == RES_CODE) {
            setResult(RES_CODE);
            finish();
        }
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            MovieRecorderActivity.this.finish();
            overridePendingTransition(R.anim.anim_slide_left_in, R.anim.anim_slide_right_out);
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}

我把那個跳出頁面就刪除的給注釋掉了,因為我要點擊這個小的,把url傳到播放的頁面讓他全屏播放。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM