VideoUtils.java 6.79 KB
package com.metroapp.forum;

import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;

import com.metroapp.MainApplication;
import com.metroapp.forum.bean.VideoBean;
import com.xiniunet.api.internal.util.StringUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by yangxia on 12/11/18.
 * 查询视频列表
 */

public class VideoUtils {


    public interface  QueryResultListener {

        void  onSuccess(List<VideoBean> list);

        void  onFailure(String message);

    }


    public void queryVideoList(QueryResultListener listener,double maxSize){
        new QueryVideoAsyTask(listener,maxSize).execute();
    }

    /**
     * 查询本地视频的方法
     */
    public List<VideoBean> queryVideoFun(double maxSize) {
        Uri mImageUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        String[] proj = { MediaStore.Video.Thumbnails._ID
                , MediaStore.Video.Thumbnails.DATA
                ,MediaStore.Video.Media.DURATION
                ,MediaStore.Video.Media.SIZE
                ,MediaStore.Video.Media.DISPLAY_NAME
                ,MediaStore.Video.Media.DATE_MODIFIED};

        String selection ;//筛选条件
        if (maxSize !=0){
            selection = MediaStore.Video.Media.MIME_TYPE + "=?" + " AND "+ MediaStore.Video.Media.SIZE +" <= "+ maxSize;
        }else{
            selection = MediaStore.Video.Media.MIME_TYPE + "=?" ;
        }
        //视频时长要大于3s
        selection = selection+" AND " + MediaStore.Video.Media.DURATION + " >= 3000" ;

        Cursor cursor = MainApplication._this.getContentResolver().query(mImageUri,
                proj,
                selection,
                new String[]{"video/mp4"},
                MediaStore.Video.Media.DATE_MODIFIED+" desc");


        ArrayList<VideoBean> videoBeanArrayList = new ArrayList<>();
        if (cursor == null) {
            return videoBeanArrayList;
        }
        try{
                while (cursor.moveToNext()){
                    final int dataColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
                    final  int durationColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION);
                    final  int sizeC = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE);
                    final  int nameC = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME);
                    String localPath = cursor.getString(dataColumn);
                    long duration = cursor.getLong(durationColumn);
                    long size =  cursor.getLong(sizeC);
                    String name = cursor.getString(nameC) ==null?"":cursor.getString(nameC);
                    String thumbnail = getVideoThumbnail(localPath,name);

                    MediaMetadataRetriever retr = new MediaMetadataRetriever();
                    retr.setDataSource(localPath);
                    String rotation = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);

                    VideoBean  videoBean = new VideoBean();
                    videoBean.setFilePath(localPath);
                    videoBean.setDuration(duration);
                    videoBean.setSize(size);
                    videoBean.setDispalyName(name);
                    videoBean.setThumbnail(thumbnail);
                    videoBean.setRotate(StringUtils.isEmpty(rotation)?0:Integer.valueOf(rotation));
                    videoBeanArrayList.add(videoBean);
                }
        }catch (NullPointerException e){

        }finally {
            cursor.close();
        }


        return videoBeanArrayList;

    }

    // 获取不带扩展名的文件名
    public  String getFileNameNoEx(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length()))) {
                return filename.substring(0, dot);
            }
        }
        return filename;
    }


    /**
     * 根据视频文件的路径获取视频的缩略图并保存到特定文件夹
     * filePath 使用 files.getPath() 或 files.getAbsolutePath() 都可以
     */
    public String getVideoThumbnail(String filePath,String name) {
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(filePath);
            bitmap = retriever.getFrameAtTime();
        } catch(IllegalArgumentException e) {
            e.printStackTrace();
        } catch (RuntimeException e) {
            e.printStackTrace();
        } finally {
            try {
                retriever.release();
            } catch (RuntimeException e) {
            e.printStackTrace();
            }
        }
        //将图片存放到文件夹路径下
        if (bitmap !=null){

            String path = Environment.getExternalStorageDirectory() + "/" + MainApplication._this.getPackageName() + "/thumb";
            path = path + '/'+getFileNameNoEx(name) + ".jpg";
            saveBitmapAsPng(bitmap,path);

            return path;

        }
        return "";
    }

    /**
     * bitmap转png
     * @param bmp
     */
    public  void saveBitmapAsPng(Bitmap bmp,String path) {
        if (StringUtils.isEmpty(path)) {
            return;
        }
        try {
            File file = new File(path);
            FileOutputStream out = new FileOutputStream(file);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
                bmp.setConfig(Bitmap.Config.RGB_565);
            }
            bmp.compress(Bitmap.CompressFormat.JPEG, 80, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public class QueryVideoAsyTask extends AsyncTask<Void,Void,Void>{
        private   QueryResultListener  listener;
        private   double maxSize;
        private  List<VideoBean> list = new ArrayList<>();

        public QueryVideoAsyTask(QueryResultListener listener,double maxSize) {
            this.listener = listener;
            this.maxSize = maxSize;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            list = queryVideoFun(maxSize);
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            if (listener !=null){
                listener.onSuccess(list);
            }
        }
    }



}