android開發(fā)之簡單視頻播放器(VideoView)

簡單視頻播放器的使用
一、簡單使用videoView和MediaController實(shí)現(xiàn)播放控制
1、添加需要的權(quán)限

 <uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION"></uses-permission>

2、設(shè)置布局

 <VideoView
            android:id="@+id/main_video"
            android:layout_width="match_parent"
            android:layout_height="240dp"
            />

3、實(shí)例化VideoView

VideoView  videoView = (VideoView) findViewById(R.id.main_video);
      MediaController  controller = new MediaController(this);//實(shí)例化控制器
//        String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"jiaoxue.mp4";
        /**
         * 本地播放
         */
//        videoView.setVideoPath("path");
        /**
         * 網(wǎng)絡(luò)播放
         */
        videoView.setVideoURI(Uri.parse("http://192.168.1.109:8080/video/jiaoxue.mp4"));

        /**
         * 將控制器和播放器進(jìn)行互相關(guān)聯(lián)
         */
        controller.setMediaPlayer(videoView);
        videoView.setMediaController(controller);

二、自定義播放器 (貼上源碼)

<?xml version="1.0" encoding="utf-8"?>
<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.zzj.myeasyvideoplaydemo.MainActivity">

    <RelativeLayout

        android:layout_width="match_parent"
        android:layout_height="240dp">
        <VideoView
            android:id="@+id/main_video"
            android:layout_width="match_parent"
            android:layout_height="240dp"
            />
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:orientation="vertical"
            android:layout_alignParentBottom="true"
            >
            <SeekBar
                android:layout_width="match_parent"
                android:layout_height="5dp"
                android:layout_marginLeft="-20dp"
                android:layout_marginRight="-20dp"
                android:max="100"
                android:indeterminate="false"
                android:progress="20"
                />
            <RelativeLayout
                android:gravity="center_vertical"
                android:background="#101010"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal"
                    >
                    <ImageView
                        android:id="@+id/play_pasue_image"
                        android:layout_marginLeft="5dp"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:background="@mipmap/video_play_blue"
                        />
                    <TextView
                        android:id="@+id/main_current_time"
                        android:layout_marginLeft="16dp"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="00:00:00"
                        android:textSize="14dp"
                        android:textColor="#ffffff"
                        />
                    <TextView
                        android:layout_marginLeft="5dp"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="/"
                        android:textSize="14dp"
                        android:textColor="#4c4c4c"
                        />
                    <TextView
                        android:id="@+id/main_totally_time"
                        android:layout_marginLeft="5dp"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="00:00:00"
                        android:textSize="14dp"
                        android:textColor="#ffffff"
                        />
                </LinearLayout>
                <LinearLayout
                    android:layout_marginRight="5dp"
                    android:layout_alignParentRight="true"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content">
                    <ImageView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:background="@mipmap/video_sound_switch"
                        />
                    <SeekBar
                        android:layout_width="100dp"
                        android:layout_height="5dp"
                        android:progress="20"
                        android:max="100"
                        />
                    <ImageView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:background="@mipmap/play"
                        />
                </LinearLayout>
            </RelativeLayout>
        </LinearLayout>
    </RelativeLayout>

</RelativeLayout>

視頻Java類:

public class TestMovieActivity extends BaseActivity {
    public static final int UPDATA_VIDEO_NUM = 1;
    private CustomVideoView videoView;
    private MediaController controller;//控制器
    private RelativeLayout videoLayout;
    private LinearLayout controllerLayout;//播放器的總控制布局
    private SeekBar play_seek, volume_seek;//播放進(jìn)度和音量控制進(jìn)度
    private ImageView play_controller_image, screen_image,volume_Image;
    private TextView current_time_tv, totally_time_tv;
    private String path;
    private int screen_width, screen_height;
    private AudioManager audioManager;//音量控制器
    private boolean screen_flag = true;//判斷屏幕轉(zhuǎn)向

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //實(shí)例化音量控制器
        audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        setContentView(R.layout.act_testmovie);

        initView();
        initData();
        initViewOnClick();
//        controller = new MediaController(this);//實(shí)例化控制器
//        path = Environment.getExternalStorageDirectory().getAbsolutePath()+"jiaoxue.mp4";
        /**
         * 本地播放
         */
//        videoView.setVideoPath("");
        /**
         * 網(wǎng)絡(luò)播放
         */
        videoView.setVideoURI(Uri.parse("http://192.168.1.109:8080/video/jiaoxue.mp4"));
        //視頻播放時開始刷新
//        videoView.start();
        play_controller_image.setImageResource(R.mipmap.video_play_blue);
//        handler.sendEmptyMessage(UPDATA_VIDEO_NUM);
        /**
         * 將控制器和播放器進(jìn)行互相關(guān)聯(lián)
         */
//        controller.setMediaPlayer(videoView);
//        videoView.setMediaController(controller);
    }

    @Override
    protected void onPause() {
        super.onPause();
        handler.removeMessages(UPDATA_VIDEO_NUM);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeMessages(UPDATA_VIDEO_NUM);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // 判斷當(dāng)前屏幕的橫豎屏狀態(tài)
        int screenOritentation = getResources().getConfiguration().orientation;
        if (screenOritentation == Configuration.ORIENTATION_LANDSCAPE) {
            //橫屏?xí)r處理
            setVideoScreenSize(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            volume_seek.setVisibility(View.VISIBLE);
            volume_Image.setVisibility(View.VISIBLE);
            screen_flag = false;
            //清除全屏標(biāo)記,重新添加
            getWindow().clearFlags((WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN));
            getWindow().addFlags((WindowManager.LayoutParams.FLAG_FULLSCREEN));
        } else {
            //豎屏?xí)r處理
            setVideoScreenSize(ViewGroup.LayoutParams.MATCH_PARENT, DisplayUtils.dp2px(mContext,240));
            screen_flag = true;
            volume_seek.setVisibility(View.GONE);
            volume_Image.setVisibility(View.GONE);
            //清除全屏標(biāo)記,重新添加
            getWindow().clearFlags((WindowManager.LayoutParams.FLAG_FULLSCREEN));
            getWindow().addFlags((WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN));
        }
    }

    /**
     * 通過handler對播放進(jìn)度和時間進(jìn)行更新
     */
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == UPDATA_VIDEO_NUM) {
                //獲取視頻播放的當(dāng)前時間
                int currentTime = videoView.getCurrentPosition();
                //獲取視頻的總時間
                int totally = videoView.getDuration();
                //格式化顯示時間
                updataTimeFormat(totally_time_tv, totally);
                updataTimeFormat(current_time_tv, currentTime);
                //設(shè)置播放進(jìn)度
                play_seek.setMax(totally);
                play_seek.setProgress(currentTime);
                //自己通知自己更新
                handler.sendEmptyMessageDelayed(UPDATA_VIDEO_NUM, 500);//500毫秒刷新
            }
        }
    };

    /**
     * 設(shè)置橫豎屏?xí)r的視頻大小
     *
     * @param width
     * @param height
     */
    private void setVideoScreenSize(int width, int height) {
        //獲取視頻控件的布局參數(shù)
        ViewGroup.LayoutParams videoViewLayoutParams = videoView.getLayoutParams();
        //設(shè)置視頻范圍
        videoViewLayoutParams.width = width;
        videoViewLayoutParams.height = height;
        videoView.setLayoutParams(videoViewLayoutParams);
        //設(shè)置視頻和控制組件的layout
        ViewGroup.LayoutParams videoLayoutLayoutParams= videoLayout.getLayoutParams();
        videoLayoutLayoutParams.width = width;
        videoLayoutLayoutParams.height = height;
        videoLayout.setLayoutParams(videoLayoutLayoutParams);
    }

    /**
     * 時間格式化
     *
     * @param textView    時間控件
     * @param millisecond 總時間 毫秒
     */
    private void updataTimeFormat(TextView textView, int millisecond) {
        //將毫秒轉(zhuǎn)換為秒
        int second = millisecond / 1000;
        //計算小時
        int hh = second / 3600;
        //計算分鐘
        int mm = second % 3600 / 60;
        //計算秒
        int ss = second % 60;
        //判斷時間單位的位數(shù)
        String str = null;
        if (hh != 0) {//表示時間單位為三位
            str = String.format("%02d:%02d:%02d", hh, mm, ss);
        } else {
            str = String.format("%02d:%02d", mm, ss);
        }
        //將時間賦值給控件
        textView.setText(str);
    }

    /**
     * 按鈕點(diǎn)擊事件
     */
    private void initViewOnClick() {
        //播放按鈕事件
        play_controller_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //判斷播放按鈕的狀態(tài)
                if (videoView.isPlaying()) {
                    play_controller_image.setImageResource(R.mipmap.video_play_blue);
                    //視頻暫停
                    videoView.pause();
                    //當(dāng)視頻處于暫停狀態(tài),停止handler的刷新
                    handler.removeMessages(UPDATA_VIDEO_NUM);
                } else {
                    play_controller_image.setImageResource(R.mipmap.video_pause_white);
                    videoView.start();
                    //當(dāng)視頻播放時,通知刷新
                    handler.sendEmptyMessage(UPDATA_VIDEO_NUM);
                }
            }
        });
        //播放進(jìn)度條事件
        play_seek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                //設(shè)置當(dāng)前的播放時間
                updataTimeFormat(current_time_tv, progress);
                if (videoView.getDuration() == progress) {
                    play_controller_image.setImageResource(R.mipmap.video_play_blue);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                //拖動視頻進(jìn)度時,停止刷新
                handler.removeMessages(UPDATA_VIDEO_NUM);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //停止拖動后,獲取總進(jìn)度
                int totall = seekBar.getProgress();
                //設(shè)置VideoView的播放進(jìn)度
                videoView.seekTo(totall);
                //重新handler刷新
                handler.sendEmptyMessage(UPDATA_VIDEO_NUM);

            }
        });
        //音量控制條事件
        volume_seek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                //設(shè)置音量變動后系統(tǒng)的值
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,progress,0);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        //設(shè)置全屏按鈕點(diǎn)擊事件
        screen_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showLog("------當(dāng)前屏幕標(biāo)記----:"+screen_flag);
                if(screen_flag){
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//控制屏幕豎屏
                }else {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//控制屏幕橫屏
                }
            }
        });
    }

    @Override
    protected void initView() {
        videoView = (CustomVideoView) findViewById(R.id.main_video);
        videoLayout = (RelativeLayout) findViewById(R.id.act_testmovie_videolayout);
        controllerLayout = (LinearLayout) findViewById(R.id.main_controller_liner);
        play_seek = (SeekBar) findViewById(R.id.main_play_seek);
        volume_seek = (SeekBar) findViewById(R.id.main_volume_seek);
        current_time_tv = (TextView) findViewById(R.id.main_current_time);
        totally_time_tv = (TextView) findViewById(R.id.main_totally_time);
        play_controller_image = (ImageView) findViewById(R.id.play_pasue_image);
        screen_image = (ImageView) findViewById(R.id.main_screen_image);
        volume_Image = (ImageView) findViewById(R.id.act_testmovies_volume_image);
        DisplayMetrics metric = new DisplayMetrics();
        screen_width = metric.widthPixels;
        screen_height = metric.heightPixels;
    }

    @Override
    protected void initData() {
        //獲取設(shè)置音量的最大值
        int volumeMax = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        volume_seek.setMax(volumeMax);
        //獲取設(shè)置當(dāng)前音量
        int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        volume_seek.setProgress(currentVolume);
    }
}

補(bǔ)上CustomVideoView

public class CustomVideoView extends VideoView {
    //聲明屏幕的大小
    int width = 1920;
    int height = 1080;
    public CustomVideoView(Context context) {
        super(context);
    }

    public CustomVideoView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public CustomVideoView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //設(shè)置寬高
        int defaultWidth = getDefaultSize(width,widthMeasureSpec);
        int defaultHeight = getDefaultSize(height,heightMeasureSpec);
        setMeasuredDimension(defaultWidth,defaultHeight);
    }
}

https://github.com/z1060932884/VideoDemo

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,983評論 25 709
  • 視頻播放器在App是很常見的,有哪些視頻播放器呢?具體情況該用哪款呢?這里我總結(jié)了常用的視屏播放Videoview...
    奔跑吧哈哈閱讀 30,133評論 2 46
  • 一些肢體語言會泄露你內(nèi)心的想法,即使這個想法你并不知道,這些,你都知道嗎?據(jù)現(xiàn)在的科學(xué)研究來看,人們所知道的肢體語...
    岳小姐閱讀 2,168評論 0 0
  • 什么狀態(tài) 我也不知道 醒的時候很難睡著 熬夜熬的煩躁 每天躺在床上但都覺得好累好累 睡的時候 戴上眼罩 想著想著事...
    我叫什么不重要閱讀 131評論 0 0
  • 昨晚朋友生日,家庭聚餐。餐后都約著去壽星家繼續(xù)娛樂。 我們幾個脾氣相投的中年少女,湊在壽星婆的閨房拉呱...
    子信521閱讀 329評論 0 0

友情鏈接更多精彩內(nèi)容