2016年8月9日 星期二

Android: Video Player

since: 2016/08/09
update: 2016/09/10

reference:
1. Android MediaPlayer and VideoView Tutorial


A. Create a Project
    1. 設定好專案相關資料後 > Next

    2. Minimum SDK 選擇 API 18: Android 4.3 (Jelly Bean)
        > Next

    3. 選擇 Empty Activity > Next

    4. Customize the Activity: 使用預設即可 > Finish

-----------------------------------------------------------------------------------------------

B. Create raw folder to store video files
    1. res > New > Directory

    2. 輸入 raw > OK

    3. Copy & Paste video files to raw folder:

-----------------------------------------------------------------------------------------------

C. Design the Interface:
     1. 點選 activity_main.xml 檔案, 將右方 Component Tree 下的元件,
        只留一個預設的 RelativeLayout, 其餘皆刪除.

     2. 切換到 Text 模式, 將 RelativeLayoutFrameLayout 取代

     3. 回到 Design 模式, 將 VideoView 元件拖拉到 FrameLayout 的中間  subview 

     4. 接著, 在所新增 VideoView 元件選取的情況下,
        將其 layout:widthlayout:height 皆設為: fill_parent

5. activity_main.xml 完成如下:
<?xml version="1.0" encoding="utf-8"?>
<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: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="cat.myhome.videoplayer.MainActivity">

    <VideoView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/videoView"
        android:layout_gravity="center" />
</FrameLayout>

-----------------------------------------------------------------------------------------------

D. 開啟 MainActivity.java 檔案, 修改如下:
package cat.myhome.videoplayer;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;


//@VideoPlayer ------
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.widget.MediaController;
import android.net.Uri;
import android.util.Log;
import android.widget.VideoView;

public class MainActivity extends AppCompatActivity {

    //@VideoPlayer ------
    private VideoView videoView;
    private int position = 0;
    private MediaController mediaController;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //@VideoPlayer ------
        videoView = (VideoView) findViewById(R.id.videoView);

        //@VideoPlayer: Set the media controller buttons ------
        if (mediaController == null) {
            mediaController = new MediaController(MainActivity.this);

            // Set the videoView that acts as the anchor for the MediaController.
            mediaController.setAnchorView(videoView);

            // Set MediaController for VideoView
            videoView.setMediaController(mediaController);
        }

        //@VideoPlayer: Set the Video URI ------
        try {
            // ID of video file.
            int id = this.getRawResIdByName("alice");
            videoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + id));

        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }

        videoView.requestFocus();

        //@VideoPlayer: When the video file ready for playback. ------
        videoView.setOnPreparedListener(new OnPreparedListener() {

            public void onPrepared(MediaPlayer mediaPlayer) {

                videoView.seekTo(position);
                if (position == 0) {
                    videoView.start();
                }

                // When video Screen change size.
                mediaPlayer.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
                    @Override
                    public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {

                        // Re-Set the videoView that acts as the anchor for the MediaController
                        mediaController.setAnchorView(videoView);
                    }
                });
            }
        });

    } // end of: onCreate


    //@VideoPlayer: Find ID corresponding to the name of the resource (in the directory raw). ------
    public int getRawResIdByName(String resName) {
        String pkgName = this.getPackageName();
        // Return 0 if not found.
        int resID = this.getResources().getIdentifier(resName, "raw", pkgName);
        Log.i("AndroidVideoView", "Res Name: " + resName + "==> Res ID = " + resID);
        return resID;
    }


    //@VideoPlayer ------
    // When you change direction of phone, this method will be called.
    // It store the state of video (Current position)

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);

        // Store current position.
        savedInstanceState.putInt("CurrentPosition", videoView.getCurrentPosition());
        videoView.pause();
    }


    //@VideoPlayer ------
    // After rotating the phone. This method is called.

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

        // Get saved position.
        position = savedInstanceState.getInt("CurrentPosition");
        videoView.seekTo(position);
    }

} // end of: class MainActivity


-----------------------------------------------------------------------------------------------

E. 執行結果:

-----------------------------------------------------------------------------------------------

F. Playing Video from URL:

    1. Declare permission to access Internet
        AndroidManifest.xml:
        ....
        <uses-permission android:name="android.permission.INTERNET"></uses-permission>

        <application>
        ....


    2. MainActivity.java
....
// Way 1:
String videoUrl="http://www.youtubemaza.com/files/data/366/Tom%20And%20Jerry%20055%20Casanova%20Cat%20(1951).mp4";    
  
Uri video = Uri.parse(videoUrl);
videoView.setVideoURI(video);



// Way 2:
String videoUrl="http://www.youtubemaza.com/files/data/366/Tom%20And%20Jerry%20055%20Casanova%20Cat%20(1951).mp4";   

videoView.setVideoPath(videoUrl);

....

沒有留言:

張貼留言

注意:只有此網誌的成員可以留言。