码迷,mamicode.com
首页 > 移动开发 > 详细

android视频播放器

时间:2016-04-26 00:34:01      阅读:253      评论:0      收藏:0      [点我收藏+]

标签:

项目设计:分为3个界面,欢迎界面,主界面,播放界面。欢迎界面,用来获取获取视频的集合,并放入全局变量中。主界面:用来显示视频相关信息。播放界面:用于播放。

一.我们在欢迎界面的时候需要获取视频的集合,并放入全局变量中。

步骤:

1.视频信息类,用来存放视频信息。

技术分享
package com.example.coolmediaplayer.entities;

import java.text.DecimalFormat;

import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.media.MediaMetadataRetriever;
import android.util.Log;

/**
 * 视频信息的实体类,用来保存视频相关信息
 * 
 * @author chen
 * 
 */
public class VideoInfo {
    private int id; // id
    private String title; // title
    private String album;
    private String artist;
    private String displayName;
    private String mimeType;
    private String path;
    private long size;
    private long duration;
    private Bitmap videoThumbnail; // 视频缩略图
    private String resolution; // 分辨率

    /**
     * 
     */
    public VideoInfo() {
        super();
    }

    /**
     * @param id
     * @param title
     * @param album
     * @param artist
     * @param displayName
     * @param mimeType
     * @param data
     * @param size
     * @param duration
     */
    public VideoInfo(int id, String title, String album, String artist, String displayName, String mimeType, String path, long size, long duration, Bitmap videoThumbnail, String resolution) {
        super();
        this.id = id;
        this.title = title;
        this.album = album;
        this.artist = artist;
        this.displayName = displayName;
        this.mimeType = mimeType;
        this.path = path;
        this.size = size;
        this.duration = duration;
        this.videoThumbnail = videoThumbnail;
        this.resolution = resolution;
    }

    public String getResolution() {
        return resolution;
    }

    public void setResolution(String resolution) {
        this.resolution = resolution;
    }

    /**
     * 获得缩略图
     * 
     * @return
     */
    public Bitmap getVideoThumbnail() {
        return videoThumbnail;
    }

    public void setVideoThumbnail(Bitmap bitmap) {
        videoThumbnail = bitmap;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAlbum() {
        return album;
    }

    public void setAlbum(String album) {
        this.album = album;
    }

    public String getArtist() {
        return artist;
    }

    public void setArtist(String artist) {
        this.artist = artist;
    }

    public String getDisplayName() {
        return displayName;
    }

    public void setDisplayName(String displayName) {
        this.displayName = displayName;
    }

    public String getMimeType() {
        return mimeType;
    }

    public void setMimeType(String mimeType) {
        this.mimeType = mimeType;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public long getSize() {
        return size;
    }

    public void setSize(long size) {
        this.size = size;
    }

    public long getDuration() {
        return duration;
    }

    public void setDuration(long duration) {
        this.duration = duration;
    }

    /**
     * HH:mm:ss
     * 
     * @return
     */
    public String getDurationStr() {
        String str = "";
        long time = this.duration / 1000;
        int s = (int) (time % 60);
        int m = (int) (time / 60 % 60);
        int h = (int) (time / 3600);
        String hString = "";
        String mString = "";
        String sString = "";
        if (h < 10) {
            hString = "0" + h;
        } else {
            hString = h + "";
        }
        if (m < 10) {
            mString = "0" + m;
        } else {
            mString = m + "";
        }
        if (s < 10) {
            sString = "0" + s;
        } else {
            sString = s + "";
        }
        str = hString + ":" + mString + ":" + sString;
        return str;
    }

    /**
     * 转化为MG/GB
     * 
     * @return
     */
    public String getSizeStr() {
        String str = "";
        DecimalFormat df = new DecimalFormat("#.0");
        long s = size / 1024 / 1024;
        if (s > 1024) {
            str = df.format(s / 1024) + "G";
            return str;
        }
        if (s < 1) {
            str = " < 1M";
            return str;
        }
        str = df.format(s) + "MB";
        return str;

    }

    /**
     * 获得本地视频的预览图
     * 
     * @param videoPath
     * @return
     */
    public static Bitmap obtainVideoThumbnail(String videoPath) {
        MediaMetadataRetriever media = new MediaMetadataRetriever();
        media.setDataSource(videoPath);
        Bitmap bitmap = media.getFrameAtTime();
        Matrix matrix = new Matrix();
        matrix.postScale(0.1f, 0.1f); // 长和宽放大缩小的比例
        Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        Log.d("h_bl", resizeBmp.getWidth() + "  X  " + bitmap.getHeight());
        bitmap.recycle();
        return resizeBmp;
    }

}
View Code

2.视频提供类,从系统自带的MediaStore获取VideoInfo

技术分享
package com.example.coolmediaplayer.utils;

import java.util.ArrayList;
import java.util.List;

import com.example.coolmediaplayer.entities.VideoInfo;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.util.Log;

/**
 * 视频提供类,从系统自带的MediaStore获取VideoInfo
 * 
 * @author chen
 * 
 */
public class VideoProvider {

    private Context context;

    /**
     * 构造方法,用来创建对象
     * 
     * @param context
     */
    public VideoProvider(Context context) {
        this.context = context;
    }

    /**
     * 从系统自带的MediaStore获取VideoInfo,获取集合
     */
    public List<VideoInfo> getVideosInfos() {
         List<VideoInfo> list = null;
        if (context != null) {
            // 游标读取content provider提供的数据
            Cursor cursor = context.getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
            if (cursor != null) {
                 list = new ArrayList<VideoInfo>();
                while (cursor.moveToNext()) {
                    int id = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID));
                    String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.TITLE));
                    String album = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.ALBUM));
                    String artist = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.ARTIST));
                    String displayName = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME));
                    String mimeType = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.MIME_TYPE));
                    String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
                    long duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION));
                    long size = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE));
                    String resolution = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.RESOLUTION));
                    Log.d("h_bl", resolution);
                    Bitmap videoThumbnail = VideoInfo.obtainVideoThumbnail(path);
                    VideoInfo video = new VideoInfo(id, title, album, artist, displayName, mimeType, path, size, duration, videoThumbnail, resolution);
                    list.add(video);
                }
                cursor.close();
            }
        }
        return list;
    }

}
View Code

3.欢迎界面,加载视频信息,并放入全局变量中。

技术分享
package com.example.coolmediaplayer;

import java.util.ArrayList;
import java.util.List;

import com.example.coolmediaplayer.app.VideoInfosApp;
import com.example.coolmediaplayer.entities.VideoInfo;
import com.example.coolmediaplayer.utils.VideoProvider;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

/**
 * 欢迎界面,加载视频信息
 * 
 * @author Chen
 * 
 */
@SuppressLint("HandlerLeak")
public class WelcomeActivity extends Activity {
    private VideoProvider provider; // 视频提供者
    private int RESULE_OK = 1; // Message的常量
    private String TAG = "Chen"; 
    private VideoInfosApp videoInfosApp; // 全局变量
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case 1:
                Log.d(TAG, "handler回调成功");
                // 延迟1s后执行
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        Intent intent = new Intent(WelcomeActivity.this, MainActivity.class);
                        startActivity(intent);
                        finish(); // 结束本Aty
                    }
                }, 1000);
                break;
            default:
                break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);// 去掉信息栏
        setContentView(R.layout.activity_welcome);
        provider = new VideoProvider(this); // 实例化VideoProvider
        videoInfosApp = (VideoInfosApp) getApplicationContext(); // 全局变量
        // 子线程,进行耗时操作
        new Thread(new Runnable() {

            @Override
            public void run() {
                List<VideoInfo> videoInfos = new ArrayList<VideoInfo>();
                // 获取到视频信息的集合,并存入全局变量中
                try {
                    videoInfos = provider.getVideosInfos();
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "视频信息有变更,正在扫描SD卡...", Toast.LENGTH_LONG).show();
                    // 通知系统扫描sd卡
                    MediaScannerConnection.scanFile(WelcomeActivity.this, new String[] { Environment.getExternalStorageDirectory().getAbsolutePath() }, null, null);
                    videoInfos = provider.getVideosInfos();  // 可能出现问题..
                } finally {
                    videoInfosApp.setList(videoInfos);
                }

                Message message = mHandler.obtainMessage();
                message.what = RESULE_OK;
                mHandler.sendMessage(message); // 通知UI更新
            }
        }).start();
    }
}
View Code

4.全局变量

技术分享
package com.example.coolmediaplayer.app;

import java.util.ArrayList;
import java.util.List;

import com.example.coolmediaplayer.entities.VideoInfo;

import android.app.Application;
import android.util.Log;

public class VideoInfosApp extends Application {
    private List<VideoInfo> list = new ArrayList<VideoInfo>();; // 视频信息集合

    public void setList(List<VideoInfo> list) {
        this.list = list;
    }

    public List<VideoInfo> getList() {
        if (list == null) {
            Log.d("Chen", "VideoInfos List<VideoInfo>为空");
            return list;
        } else {
            Log.d("Chen", "VideoInfos List<VideoInfo>为不空");
            return list;
        }
    }
}
View Code

欢迎界面的布局:

技术分享
<RelativeLayout 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="@drawable/welcome_cool"
    tools:context="com.example.coolmediaplayer.WelcomeActivity" >

    
</RelativeLayout>
View Code

二.主界面用ListView显示视频信息

技术分享
package com.example.coolmediaplayer;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.example.coolmediaplayer.adapter.MyAdapterWithCommAdapter;
import com.example.coolmediaplayer.app.VideoInfosApp;
import com.example.coolmediaplayer.entities.VideoInfo;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;

public class MainActivity extends Activity implements OnClickListener {
    private ListView main_lv_video; // 视频的listview
    private ImageButton main_imgBt_back; // 返回按钮
    private List<VideoInfo> videoInfos = new ArrayList<VideoInfo>(); // 视频信息集合
    private MyAdapterWithCommAdapter mAdapterWithCommAdapter; // listview适配器
    private String TAG = "Chen";
    private VideoInfosApp videoInfosApp; // 获取全局变量的视频信息

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        init();
        main_lv_video.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
                Intent intent = new Intent(MainActivity.this, PlayActivity.class);
                intent.putExtra("clickPosition", position);
                startActivity(intent);
            }
        });
        main_lv_video.setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View view, int position, long id) {
                DeleteDialog(position);
                return true;
            }
        });
    }

    /**
     * 初始化操作
     */
    private void init() {
        main_lv_video = (ListView) findViewById(R.id.main_lv_video);  // 初始化listview
        main_imgBt_back = (ImageButton) findViewById(R.id.main_imgBt_back);  // 初始化返回按钮
        main_imgBt_back.setOnClickListener(this);  // 返回按钮点击事件
        videoInfosApp = (VideoInfosApp) getApplicationContext();  // 获取全局变量的视频信息
        videoInfos = videoInfosApp.getList();
        Log.d(TAG, "videoInfosApp.getList()=" + videoInfosApp.getList());
        mAdapterWithCommAdapter = new MyAdapterWithCommAdapter(this, videoInfos, R.layout.video_item);
        // 添加适配器
        main_lv_video.setAdapter(mAdapterWithCommAdapter);
    }

    /**
     * 删除视频文件
     */
    private void DeleteDialog(int position) {
        AlertDialog.Builder builder = new Builder(MainActivity.this);
        final int p = position;
        builder.setMessage("是否删除该文件?");
        builder.setTitle("温馨提示");

        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                deleteMusic(p); //删除文件
                // 通知adapter 更新
                videoInfos.remove(p);
                mAdapterWithCommAdapter.notifyDataSetChanged();
            }
        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.create().show();
    }

    /**
     * 删除文件,并通知系统更新媒体库
     * 
     * @param position
     */
    private void deleteMusic(int position) {
        // 这里File构造方法参数就是从你list读取的文件路径
        String path = videoInfos.get(position).getPath();
        File file = new File(path);
        file.delete();
        // MediaScannerConnection.scanFile(this, new String[] {
        // Environment.getExternalStorageDirectory().getAbsolutePath() }, null,
        // null);
        MediaScannerConnection.scanFile(this, new String[] { path }, null, null);
        Log.d(TAG, "删除文件执行完毕");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.main_imgBt_back:
            finish();
            break;
        default:
            break;
        }
    }
}
View Code

list适配器adapter:

技术分享
package com.example.coolmediaplayer.adapter;

/*
 * @Title MyAdapterWithCommViewHolder.java
 * @Copyright Copyright 2010-2015 Yann Software Co,.Ltd All Rights Reserved.
 * @Description:
 * @author Yann
 * @date 2015-8-5 下午10:03:45
 * @version 1.0
 */

import java.util.List;

import com.example.coolmediaplayer.R;
import com.example.coolmediaplayer.entities.VideoInfo;
import com.example.coolmediaplayer.utils.CommonAdapter;
import com.example.coolmediaplayer.utils.ViewHolder;

import android.content.Context;

/**
 * 类注释
 * 
 * @author Yann
 * @date 2015-8-5 下午10:03:45
 */
public class MyAdapterWithCommAdapter extends CommonAdapter<VideoInfo> {
    public MyAdapterWithCommAdapter(Context context, List<VideoInfo> datas,
            int layoutId) {
        super(context, datas, layoutId);
    }

    /**
     * 实现public abstract View getView(int position, View convertView, ViewGroup
     * parent);
     * 
     * @see android.widget.Adapter#getView(int, android.view.View,
     *      android.view.ViewGroup)
     */
    /*
     * @Override public View getView(int position, View convertView, ViewGroup
     * parent) { ViewHolder holder = ViewHolder.get(mContext, convertView,
     * parent, R.layout.item, position); Bean bean = mDatas.get(position);
     * 
     * ((TextView)holder.getView(R.id.tv_title)).setText(bean.getTitle());
     * ((TextView)holder.getView(R.id.tv_desc)).setText(bean.getDesc());
     * ((TextView)holder.getView(R.id.tv_time)).setText(bean.getTime());
     * ((TextView)holder.getView(R.id.tv_phone)).setText(bean.getPhone());
     * 
     * return holder.getConvertView(); }
     */

    /**
     * 实现public abstract void convert(ViewHolder holder, T t);
     * 
     * @see com.imooc.baseadapter.utils.CommonAdapter#convert(com.imooc.baseadapter.utils.ViewHolder,
     *      java.lang.Object)
     */
    @Override
    public void convert(ViewHolder holder, final VideoInfo videoInfo) {
        /*
         * ((TextView)holder.getView(R.id.tv_title)).setText(bean.getTitle());
         * ((TextView)holder.getView(R.id.tv_desc)).setText(bean.getDesc());
         * ((TextView)holder.getView(R.id.tv_time)).setText(bean.getTime());
         * ((TextView)holder.getView(R.id.tv_phone)).setText(bean.getPhone());
         */
        holder.setText(R.id.video_item_title, videoInfo.getTitle())
                .setText(R.id.video_item_duration, videoInfo.getDurationStr())
                .setText(R.id.video_item_size, videoInfo.getSizeStr());

         holder.setImage(R.id.video_item_img, videoInfo.getVideoThumbnail());

    }
}
View Code

相关工具类,用于通用的适配器adapter

技术分享
package com.example.coolmediaplayer.utils;

/*
 * @Title ViewHolder.java
 * @Copyright Copyright 2010-2015 Yann Software Co,.Ltd All Rights Reserved.
 * @Description:
 * @author Yann
 * @date 2015-8-5 下午9:08:31
 * @version 1.0
 */


import android.content.Context;
import android.graphics.Bitmap;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

/** 
 * 类注释
 * @author Yann
 * @date 2015-8-5 下午9:08:31
 */
public class ViewHolder
{
    private SparseArray<View> mViews;
    private int mPosition;
    private View mConvertView;

    public View getConvertView()
    {
        return mConvertView;
    }

    public ViewHolder(Context context, ViewGroup parent, int layoutId, int position)
    {
        this.mViews = new SparseArray<View>();
        this.mPosition = position;
        this.mConvertView = LayoutInflater.from(context).inflate(layoutId, parent, false);
        this.mConvertView.setTag(this);
    }
    
    public static ViewHolder get(Context context, View convertView, 
            ViewGroup parent, int layoutId, int position)
    {
        if (null == convertView)
        {
            return new ViewHolder(context, parent, layoutId, position);
        }
        else
        {
            ViewHolder holder = (ViewHolder) convertView.getTag();
            holder.mPosition = position;
            
            return holder;
        }
    }
    
    /** 
     * 通过viewId获取控件
     * @param viewId
     * @return
     * @return T
     * @author Yann
     * @date 2015-8-5 下午9:38:39
     */ 
    public <T extends View>T getView(int viewId)
    {
        View view = mViews.get(viewId);
        
        if (null == view)
        {
            view = mConvertView.findViewById(viewId);
            mViews.put(viewId, view);
        }
        
        return (T) view;
    }
    
    /** 
     * 给ID为viewId的TextView设置文字text,并返回this
     * @param viewId
     * @param text
     * @return
     * @return ViewHolder
     * @author Yann
     * @date 2015-8-5 下午11:05:17
     */ 
    public ViewHolder setText(int viewId, String text)
    {
        TextView tv = getView(viewId);
        tv.setText(text);
        
        return this;
    } 
    /** 
     * 给ID为viewId的imgView设置文字Bitmap,并返回this
     * @param viewId
     * @param text
     * @return
     * @return ViewHolder
     * @author Yann
     * @date 2015-8-5 下午11:05:17
     */ 
    public ViewHolder setImage(int viewId, Bitmap bm)
    {
        ImageView imageView = getView(viewId);
        imageView.setImageBitmap(bm);
        return this;
    } 
}
View Code
技术分享
package com.example.coolmediaplayer.utils;

/*
 * @Title CommonAdapter.java
 * @Copyright Copyright 2010-2015 Yann Software Co,.Ltd All Rights Reserved.
 * @Description:
 * @author Yann
 * @date 2015-8-5 下午10:39:05
 * @version 1.0
 */

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

/** 
 * 类注释
 * @author Yann
 * @date 2015-8-5 下午10:39:05
 */
public abstract class CommonAdapter<T> extends BaseAdapter
{
    protected Context mContext;
    protected List<T> mDatas;
    protected LayoutInflater mInflater;
    protected int mlayoutId;
    
    public CommonAdapter(Context context, List<T> datas, int layoutId)
    {
        this.mContext = context;
        this.mDatas = datas;
        this.mlayoutId = layoutId;
        mInflater = LayoutInflater.from(context);
    }
    
    /**
     * @see android.widget.Adapter#getCount()
     */
    @Override
    public int getCount()
    {
        return mDatas.size();
    }

    /**
     * @see android.widget.Adapter#getItem(int)
     */
    @Override
    public T getItem(int position)
    {
        return mDatas.get(position);
    }

    /**
     * @see android.widget.Adapter#getItemId(int)
     */
    @Override
    public long getItemId(int position)
    {
        return position;
    }

    /**
     * @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup)
     */
//    @Override
//    public abstract View getView(int position, View convertView, ViewGroup parent);
    
    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        ViewHolder holder = ViewHolder.get(mContext, convertView, parent, mlayoutId, position);
        
        convert(holder, getItem(position));
        
        return holder.getConvertView();
    }
    
    public abstract void convert(ViewHolder holder, T t);
}
View Code

布局文件main:

技术分享
<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:orientation="vertical"
    tools:context="com.example.coolmediaplayer.MainActivity" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:background="#008B00"
        android:gravity="center_vertical"
        android:orientation="horizontal" >

        <ImageButton
            android:id="@+id/main_imgBt_back"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_marginLeft="16dp"
            android:background="@drawable/ic_back" />

        <TextView
            android:layout_marginLeft="10dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="本地视频" 
            android:gravity="center"
            android:textSize="18sp"
            android:textColor="#fff"/>
    </LinearLayout>

    <ListView
        android:id="@+id/main_lv_video"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </ListView>

</LinearLayout>
View Code

布局文件list_item:

技术分享
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="110dp"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/video_item_img"
        android:layout_width="104dp"
        android:layout_height="78dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:src="@drawable/default_cool" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="20dp"
        android:gravity="center_vertical"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/video_item_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="获取不到文件名"
            android:textSize="15sp" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="6dp"
            android:orientation="horizontal" >

            <TextView
                android:id="@+id/video_item_duration"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="获取不到时长信息"
                android:textSize="14sp" />

            <TextView
                android:id="@+id/video_item_size"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="8dp"
                android:text="获取不到大小"
                android:textSize="14sp" />
        </LinearLayout>
    </LinearLayout>

</LinearLayout>
View Code

三.播放界面:

技术分享
package com.example.coolmediaplayer;

import java.util.ArrayList;
import java.util.List;

import com.example.coolmediaplayer.app.VideoInfosApp;
import com.example.coolmediaplayer.entities.CustomVideoView;
import com.example.coolmediaplayer.entities.VideoInfo;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.MediaController;
import android.widget.TextView;

@SuppressLint("HandlerLeak")
public class PlayActivity extends Activity {
    private List<VideoInfo> videoInfos = new ArrayList<VideoInfo>(); // 视频信息集合
    private int clickPosition; // listView点击的位置
    private CustomVideoView customVideoView; // 自定义的VideoView
    private Button play_bt_back; // 返回按钮
    private FrameLayout play_operation_bar; // 操作栏
    private String TAG = "Chen";
    private long currentPosition; // 播放到当前位置
    private MediaController mediaController; // 播放控制栏
    private TextView play_tv_title; // 显示title
    private ImageButton play_bt_zoom; // 缩放按钮
    private float ratio;// 视频比例
    private boolean zoomOfSmall = false; // 是否缩小
    private int screenWidth; // 屏幕宽度
    private int screenHeight;
    private float downY;// 获取点击y坐标
    private Window window;// 用于设置亮度
    private WindowManager.LayoutParams lp; // 用于设置亮度
    private float currentBrightness = 0.8f; // 当前亮度
    private float brightnessRatio = 0; // 调整亮度
    private FrameLayout play_brightness_bar;// 显示亮度的框
    private TextView play_tv_brightness; // 亮度的文本

    private AudioManager mAudioManager; // 声音控制
    private int maxVolume;// 最大音量
    private int currentVolume; // 当前音量
    private float VolumeRatio = 0; // 调整亮度
    private boolean TouchLeft = true; // 触碰的是左侧吗?
    private FrameLayout play_voice_bar;// 显示声音的框
    private TextView play_tv_voice; // 声音的文本
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case 1:
                play_operation_bar.setVisibility(View.GONE);
                break;
            default:
                break;
            }
            super.handleMessage(msg);
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);// 去掉信息栏
        setContentView(R.layout.activity_play);
        init();
        // 播放网络视频
        // Uri uri = Uri.parse(path);
        // videoView.setVideoURI(uri);
        customVideoView.requestFocus();// 获得焦点
        customVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                // 播放结束后的动作
                finish();
            }
        });
        play_bt_back.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish(); // 返回
            }
        });
        play_bt_zoom.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                if (zoomOfSmall) {
                    FrameLayout.LayoutParams Params = (FrameLayout.LayoutParams) customVideoView.getLayoutParams(); // 取控件customVideoView当前的布局参数
                    Params.height = (int) (customVideoView.getHeight() / 0.75);// 获取当前高度/0.75
                    Params.width = (int) (customVideoView.getWidth() / 0.75); // 获取当前宽度
                                                                                // /0.75
                    customVideoView.setLayoutParams(Params); // 使设置好的布局参数应用到控件
                    play_bt_zoom.setBackgroundResource(R.drawable.ic_small);
                    zoomOfSmall = false;
                } else {
                    FrameLayout.LayoutParams Params = (FrameLayout.LayoutParams) customVideoView.getLayoutParams(); // 取控件customVideoView当前的布局参数
                    Params.height = (int) (customVideoView.getHeight() * 0.75);// 获取当前高度*0.75
                    Params.width = (int) (customVideoView.getWidth() * 0.75);// 获取当前宽度*0.75
                    customVideoView.setLayoutParams(Params); // 使设置好的布局参数应用到控件
                    play_bt_zoom.setBackgroundResource(R.drawable.ic_big);
                    zoomOfSmall = true;
                }
            }
        });
    }

    /**
     * 初始化
     */
    private void init() {
        videoInfos = new ArrayList<VideoInfo>(); // 视频信息集合初始化
        VideoInfosApp videoInfosApp = (VideoInfosApp) getApplicationContext();
        videoInfos = videoInfosApp.getList(); // 获得全局变量,并赋值给videoInfos
        Intent intent = getIntent();
        clickPosition = intent.getIntExtra("clickPosition", 0); // 获取点击的位置
        Log.d(TAG, "clickPosition=" + clickPosition);
        VideoInfo vInfo = videoInfos.get(clickPosition); // 获取点击位置的视频
        play_bt_back = (Button) findViewById(R.id.play_bt_back); // 返回按钮
        play_operation_bar = (FrameLayout) findViewById(R.id.play_operation_bar); // 操作栏
        play_tv_title = (TextView) findViewById(R.id.play_tv_title); // title
        customVideoView = (CustomVideoView) findViewById(R.id.play_vv); // 自定义customVideoView
        play_bt_zoom = (ImageButton) findViewById(R.id.play_bt_zoom); // 找到这个按钮的id,并实例化,就可以对这个按钮进行操作了。
        play_brightness_bar = (FrameLayout) findViewById(R.id.play_brightness_bar);
        play_tv_brightness = (TextView) findViewById(R.id.play_tv_brightness); // 亮度文本
        play_voice_bar = (FrameLayout) findViewById(R.id.play_voice_bar);
        play_tv_voice = (TextView) findViewById(R.id.play_tv_voice);// 声音文本

        play_tv_title.setText(vInfo.getTitle()); // 设置title信息
        mediaController = new MediaController(this); // 播放控制栏初始化
        customVideoView.setMediaController(mediaController);
        customVideoView.setVideoPath(vInfo.getPath()); // 播放 视频 路径
        Log.d(TAG, vInfo.getPath());
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        screenWidth = metric.widthPixels; // 手机屏幕宽度(像素)
        screenHeight = metric.heightPixels; // 手机屏幕高度(像素)
        ratio = ((float) vInfo.getVideoThumbnail().getWidth()) / ((float) vInfo.getVideoThumbnail().getHeight());
        Log.d(TAG, "ratio=" + ratio);
        FrameLayout.LayoutParams Params = (FrameLayout.LayoutParams) customVideoView.getLayoutParams(); // 取控件textView当前的布局参数
        Params.height = (int) (screenWidth / ratio);
        Params.width = screenWidth;
        customVideoView.setLayoutParams(Params); // 使设置好的布局参数应用到控件
        if (ratio > 1) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);// 强制为横屏
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);// 强制为竖屏
        }
        window = PlayActivity.this.getWindow();
        lp = window.getAttributes();
        lp.screenBrightness = currentBrightness; // brightness是一个0.0-1.0之间的一个float类型数值
        window.setAttributes(lp);

        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); // 声音控制
        // 最大音量
        maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        // 当前音量
        currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        Log.d(TAG, "currentVolume="+currentVolume);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            if (event.getX() > (screenWidth / 2)) {
                TouchLeft = false;
            } else {
                TouchLeft = true;
            }
            downY = event.getY();
            if (mediaController.isShowing()) {
                play_operation_bar.setVisibility(View.VISIBLE);
                // 隐藏
                mHandler.removeMessages(1); // 移除msg
                mHandler.sendEmptyMessageDelayed(1, 3000);
            } else {
                play_operation_bar.setVisibility(View.GONE);
            }
            break;
        case MotionEvent.ACTION_MOVE:
            if (TouchLeft) {
                play_brightness_bar.setVisibility(View.VISIBLE);
                float moveY = event.getY() - downY;
                if (moveY < 0) {
                    // 上滑
                    brightnessRatio = -moveY / (screenHeight / 2); // 正数
                    if (currentBrightness + brightnessRatio > 1) {
                        lp.screenBrightness = 1.0f;
                        window.setAttributes(lp);
                        play_tv_brightness.setText("100%");
                    } else {
                        lp.screenBrightness = brightnessRatio + currentBrightness;
                        Log.d(TAG, "brightnessRatio + currentBrightness=" + ((int) ((brightnessRatio + currentBrightness) * 100)));
                        window.setAttributes(lp);
                        play_tv_brightness.setText(((int) ((brightnessRatio + currentBrightness) * 100)) + "%");
                    }
                } else {
                    // 下滑
                    brightnessRatio = -moveY / (screenHeight / 2); // 负数
                    if (currentBrightness + brightnessRatio < 0.3) {
                        lp.screenBrightness = 0.3f;
                        window.setAttributes(lp);
                        play_tv_brightness.setText("30%");
                    } else {
                        lp.screenBrightness = brightnessRatio + currentBrightness;
                        window.setAttributes(lp);
                        play_tv_brightness.setText(((int) ((brightnessRatio + currentBrightness) * 100)) + "%");
                    }
                }
                break;
            } else {
                play_voice_bar.setVisibility(View.VISIBLE);
                float moveY = event.getY() - downY;
                if (moveY < 0) {
                    // 上滑
                    VolumeRatio = -moveY / (screenHeight / 2); // 正数
                //    Log.d(TAG, "VolumeRatio="+((int) (VolumeRatio * maxVolume)));
                //    Log.d(TAG, "currentVolume + ((int) (VolumeRatio * maxVolume))="+currentVolume + ((int) (VolumeRatio * maxVolume)));
                    if (currentVolume + ((int) (VolumeRatio * maxVolume)) > maxVolume) {
                        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume, 0); // tempVolume:音量绝对值
                        play_tv_voice.setText("100%");
                    } else {
                        int v = currentVolume + ((int) (VolumeRatio * maxVolume));
                        Log.d(TAG, "v="+v);
                        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, v, 0); // tempVolume:音量绝对值
                        String s = ((int) (((float) v) / maxVolume * 100)) + "%";
                        play_tv_voice.setText(s);

                    }
                } else {
                    // 下滑
                    VolumeRatio = -moveY / (screenHeight / 2); // 负数
                //    Log.d(TAG, "VolumeRatio="+((int) (VolumeRatio * maxVolume)));
                    if (currentVolume + ((int) (VolumeRatio * maxVolume)) < 0) {
                        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0); // tempVolume:音量绝对值
                        play_tv_voice.setText("0%");
                    } else {
                        int v = currentVolume + ((int) (VolumeRatio * maxVolume));
                        Log.d(TAG, "v="+v);
                        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, v, 0); // tempVolume:音量绝对值
                        String s = ((int) (((float) v) / maxVolume * 100)) + "%";
                        play_tv_voice.setText(s);
                    }
                }
                break;
            }

        case MotionEvent.ACTION_UP:
            if (TouchLeft) {
                play_brightness_bar.setVisibility(View.GONE);
                if (currentBrightness + brightnessRatio > 1) {
                    currentBrightness = 1.0f;
                    break;
                }
                if (currentBrightness + brightnessRatio < 0) {
                    currentBrightness = 0.3f;
                    break;
                }
                currentBrightness += brightnessRatio;
                Log.d(TAG, "释放=" + currentBrightness + "-----   " + brightnessRatio);
                brightnessRatio = 0;
                break;
            } else {
                play_voice_bar.setVisibility(View.GONE);
                if (currentVolume + ((int) (VolumeRatio * 60)) > 60) {
                    currentVolume = 60;
                    break;
                }
                if (currentVolume + ((int) (VolumeRatio * 60)) < 0) {
                    currentVolume = 0;
                    break;
                }
                currentVolume += ((int) (VolumeRatio * 60));
                Log.d(TAG, "释放=" + currentVolume + "-----   " + VolumeRatio);
                VolumeRatio = 0;
                break;
            }
        default:
            break;
        }
        return true;
    }

    @Override
    protected void onStart() {
        Log.d(TAG, "PlayActivity  onStart");
        super.onStart();
    }

    @Override
    protected void onPause() {
        currentPosition = customVideoView.getCurrentPosition();
        Log.d(TAG, "PlayActivity  onPause" + "  currentPosition=" + currentPosition);
        super.onPause();
    }

    @Override
    protected void onResume() {
        Log.d(TAG, "currentPosition:" + currentPosition);
        Log.d(TAG, "currentPosition:" + (((int) currentPosition) - 2));
        if (currentPosition < 2000) {
            currentPosition = 0;
            customVideoView.seekTo((int) currentPosition);
            customVideoView.start();
        } else {
            int msec = (int) (currentPosition - 2000);
            customVideoView.seekTo(msec);
            customVideoView.start();
        }
        Log.d(TAG, "PlayActivity  onResume");
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        Log.d(TAG, "PlayActivity  onDestroy");
        customVideoView.stopPlayback();
        super.onDestroy();
    }

}
View Code

播放界面,需要用到CustomVideoView

技术分享
package com.example.coolmediaplayer.entities;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.VideoView;

public class CustomVideoView extends VideoView {
    private int mVideoWidth;
    private int mVideoHeight;
    // 构造方法
    public CustomVideoView(Context context) {
        super(context);
    }

    // 构造方法
    public CustomVideoView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    // 构造方法
    public CustomVideoView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // 下面的代码是让视频的播放的长宽是根据你设置的参数来决定
        int width = getDefaultSize(mVideoWidth, widthMeasureSpec);
        int height = getDefaultSize(mVideoHeight, heightMeasureSpec);
        setMeasuredDimension(width, height);
    }

}
View Code

播放的布局:

技术分享
<FrameLayout 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="#000"
    android:gravity="center"
    tools:context="com.example.coolmediaplayer.PlayActivity" >

    <com.example.coolmediaplayer.entities.CustomVideoView
        android:id="@+id/play_vv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center" />

    <FrameLayout
        android:id="@+id/play_brightness_bar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="gone" >

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

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:orientation="horizontal" >

                <ImageView
                    android:layout_width="40dp"
                    android:layout_height="40dp"
                    android:background="@drawable/ic_brightness" />

                <TextView
                    android:id="@+id/play_tv_brightness"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginLeft="4dp"
                    android:hint="亮度"
                    android:textColor="#ecf0f1"
                    android:textSize="14sp" />
            </LinearLayout>
        </RelativeLayout>
    </FrameLayout>

    <FrameLayout
        android:id="@+id/play_voice_bar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="gone" >

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

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:orientation="horizontal" >

                <ImageView
                    android:layout_width="40dp"
                    android:layout_height="40dp"
                    android:background="@drawable/ic_voice" />

                <TextView
                    android:id="@+id/play_tv_voice"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginLeft="4dp"
                    android:hint="声音"
                    android:textColor="#ecf0f1"
                    android:textSize="14sp" />
            </LinearLayout>
        </RelativeLayout>
    </FrameLayout>

    <FrameLayout
        android:id="@+id/play_operation_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#7f000000"
        android:visibility="gone" >

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

            <Button
                android:id="@+id/play_bt_back"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_alignParentLeft="true"
                android:layout_centerVertical="true"
                android:layout_marginLeft="10dp"
                android:background="@drawable/ic_back" />

            <TextView
                android:id="@+id/play_tv_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginLeft="15dp"
                android:layout_toRightOf="@id/play_bt_back"
                android:text="Title"
                android:textColor="#fff"
                android:textSize="14sp" />

            <ImageButton
                android:id="@+id/play_bt_zoom"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:layout_marginRight="16dp"
                android:background="@drawable/ic_small" />
        </RelativeLayout>
    </FrameLayout>

</FrameLayout>
View Code

 

android视频播放器

标签:

原文地址:http://www.cnblogs.com/H-BolinBlog/p/5433328.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!