Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

多媒體播放器(二):實作全螢幕視頻播放

編輯:關於 Android 程式設計

本文要實作一個播放器的全螢幕播放功能。視頻播放器的核心是 VideoView。

在 Android Studio 中若直接讓 Activity 進入全橫屏可能會閃退,解法是把運行類的父類改回 Activity 即可。實作全螢幕有兩種方式:一種是透過 XML 設定,另一種是在運行類中用程式碼實現。

第一種:XML 設定

在清單檔 AndroidManifest.xml 中,於 Activity 標籤加入 android:screenOrientation="landscape" 鎖定為橫屏;於 application 標籤加入 android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" 進入全螢幕。

由於視頻來自網路連結,別忘了加入 INTERNET 權限:

<manifest package="com.example.szh.day10"
    xmlns:android="https://schemas.android.com/apk/res/android">
    <uses-permission android:name="android.permission.INTERNET" />
</manifest>

第二種:程式碼實現

在運行類中加入以下程式碼即可全螢幕:

requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);

要注意的是,若主畫面要跳轉到全螢幕播放的 Activity,不宜在該類加上 requestWindowFeature(Window.FEATURE_NO_TITLE),否則會讓主畫面也失去標題(若就是想無標題則可設定)。此外,該類別若不繼承 Activity,點擊播放會閃退。

想達到的效果如下:


主要目標是實現全螢幕,因此先不追求其他完善功能,視頻檔案也是指定的網路檔,沒有緩衝等處理。主畫面很簡單,只是一個按鈕,點擊後開啟全螢幕播放。布局如下:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.szh.day10.Index">
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="player3"
        android:text="播放" />
</RelativeLayout>

主畫面的 Activity:

public class Index extends ActionBarActivity {
    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_index);
    }
    public void player3(View view) {
        startActivity(new Intent(this, VideoViewActivity.class));
    }
}

第二個畫面負責全螢幕播放,已具備的功能:

1、全螢幕下可左右滑動定位播放進度(這裡以 1 秒為單位)。
2、SeekBar 可拖動定位到指定位置播放。
3、暫停。
4、播放。
5、停止。
6、單擊播放器會出現控制器,2 秒後自動隱藏,顯示與隱藏都帶有簡單動畫。

public class VideoViewActivity extends Activity {
    private VideoView videoView;
    private SeekBar seekBar;
    private Timer timer;          // Java SE 計時器
    private TimerTask timerTask;  // 任務
    private LinearLayout control; // 控制器布局
    private int pause = 0;        // 暫停時的進度
    private int startX;           // 按下時的 X 座標
    int seek = 0;                 // 左右滑動時更新 SeekBar 的值
    int up = 0;                   // 按下與離開的座標差,用來判斷滑動方向
    int change = 0;               // 滑動的座標變化

    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_view);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        control = (LinearLayout) findViewById(R.id.control);
        seekBar = (SeekBar) findViewById(R.id.sb);
        videoView = (VideoView) findViewById(R.id.videoView);

        videoView.setVideoPath("https://.../video.flv");
        videoView.start();

        // 準備完成後才能取得時長並設定 SeekBar 最大值,
        // 若寫在 start() 之後會取不到時長
        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override public void onPrepared(MediaPlayer mp) {
                int duration = videoView.getDuration();
                seekBar.setMax(duration);
            }
        });

        // 每秒更新一次 SeekBar 進度
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override public void run() {
                int progess = videoView.getCurrentPosition();
                seekBar.setProgress(progess);
            }
        };
        timer.schedule(timerTask, 0, 1000);

        // 拖動 SeekBar 後定位播放
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override public void onProgressChanged(SeekBar sb, int progress, boolean fromUser) { }
            @Override public void onStartTrackingTouch(SeekBar sb) { }
            @Override public void onStopTrackingTouch(SeekBar sb) {
                videoView.seekTo(sb.getProgress());
            }
        });
    }

    public void start(View view) {
        if (pause != 0) {
            videoView.start();
            videoView.seekTo(pause);
            pause = 0;
        } else if (!videoView.isPlaying() && pause == 0) {
            videoView.start();
        }
    }

    public void pause(View view) {
        videoView.pause();
        pause = videoView.getCurrentPosition();
    }

    public void stop(View view) {
        videoView.seekTo(0);
        videoView.pause();
    }

    @Override protected void onDestroy() {
        timer.cancel();
        timerTask.cancel();
        timer = null;
        timerTask = null;
        super.onDestroy();
    }

    @Override public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startX = (int) event.getX();
                up = 0;
                if (control.getVisibility() == View.VISIBLE) {
                    control.setVisibility(View.INVISIBLE);
                    TranslateAnimation ta = new TranslateAnimation(
                            Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0,
                            Animation.RELATIVE_TO_SELF, 0F, Animation.RELATIVE_TO_SELF, 1.0F);
                    ta.setDuration(200);
                    control.startAnimation(ta);
                } else if (control.getVisibility() == View.INVISIBLE) {
                    control.setVisibility(View.VISIBLE);
                    TranslateAnimation ta = new TranslateAnimation(
                            Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0,
                            Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0f);
                    ta.setDuration(200);
                    control.startAnimation(ta);
                    // 2 秒後自動隱藏控制器
                    new Thread() {
                        @Override public void run() {
                            try { Thread.sleep(2000); }
                            catch (InterruptedException e) { e.printStackTrace(); }
                            runOnUiThread(new Runnable() {
                                @Override public void run() {
                                    control.setVisibility(View.INVISIBLE);
                                    TranslateAnimation ta = new TranslateAnimation(
                                            Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0,
                                            Animation.RELATIVE_TO_SELF, 0F, Animation.RELATIVE_TO_SELF, 1.0F);
                                    ta.setDuration(200);
                                    control.startAnimation(ta);
                                }
                            });
                        }
                    }.start();
                }
                break;
            case MotionEvent.ACTION_MOVE:
                change = (int) event.getX();
                up = startX - change;
                break;
            case MotionEvent.ACTION_UP:
                up = 0;
                break;
        }
        // up 為負代表向右滑,反之向左
        if (up < 0) {
            int seek = videoView.getCurrentPosition() + 1000;
            if (seek <= videoView.getDuration()) videoView.seekTo(seek);
        } else if (up > 0) {
            int seek = videoView.getCurrentPosition() - 1000;
            if (seek >= 0) videoView.seekTo(seek);
        }
        return super.onTouchEvent(event);
    }
}

主清單檔如下:

<manifest package="com.example.szh.day10"
    xmlns:android="https://schemas.android.com/apk/res/android">
    <uses-permission android:name="android.permission.INTERNET" />
</manifest>

使用工具:Android Studio。目前功能尚不完善,日後有空會繼續完善,目標是把它做成一個功能齊全的視頻播放器。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved