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

Android VideoView 播放影片的完整步驟與範例

編輯:關於 Android 程式設計

VideoView 是播放本地或網路影片最省事的選擇,它把 SurfaceView、MediaPlayer 與播放控制打包在一起,幾行程式碼就能跑起來。

三個基本步驟

1. 建立 VideoView——在版面配置檔中宣告,或在程式碼中 new 出來。

2. 載入影片來源——兩個方法擇一:

· setVideoPath(String path):以檔案路徑載入。
· setVideoURI(Uri uri):以 Uri 載入,可用於 content:// 或 https:// 來源。

3. 控制播放——呼叫 start()、pause()、stopPlayback()。注意原範例寫的 psuse() 是拼字錯誤,正確的 API 名稱是 pause()。

若不想自己實作播放/暫停的 UI,可搭配 MediaController,它會自動提供進度條與控制按鈕。

版面配置

<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=".MainActivity" >

    <VideoView
        android:id="@+id/video1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

Activity 實作

package com.android.xiong.vidoviewtest;

import java.io.File;
import android.app.Activity;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;

public class MainActivity extends Activity {

    private VideoView video1;
    private MediaController mediaco;

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

        video1 = (VideoView) findViewById(R.id.video1);
        mediaco = new MediaController(this);

        File file = new File("/mnt/sdcard/通話錄音/1.mp4");
        if (file.exists()) {
            video1.setVideoPath(file.getAbsolutePath());

            // VideoView 與 MediaController 互相關聯(雙向設定是必要的)
            video1.setMediaController(mediaco);
            mediaco.setMediaPlayer(video1);

            // 讓 VideoView 取得焦點,才能接收 MediaController 的按鍵
            video1.requestFocus();
        }
    }
}

setMediaController() 與 setMediaPlayer() 必須成對呼叫,前者讓 VideoView 知道要用哪個控制器,後者讓控制器知道要操作哪個播放器。少了任何一個,控制列都不會出現。

實務上必須補的幾件事

一、版面配置不能寫死路徑。直接寫 /mnt/sdcard/... 在新版 Android 上會失敗,應改用:

File dir = new File(Environment.getExternalStorageDirectory(), "通話錄音");
File file = new File(dir, "1.mp4");

並記得宣告 READ_EXTERNAL_STORAGE 權限,Android 6.0 起還需執行期動態申請。

二、要處理生命週期。VideoView 在 Activity 進入背景時不會自動暫停,繼續播放會浪費電力。建議:

@Override
protected void onPause() {
    super.onPause();
    if (video1 != null && video1.isPlaying()) {
        video1.pause();
    }
}

三、設定螢幕保持恆亮。播放時螢幕自動關閉是很糟糕的體驗:

video1.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
    @Override
    public void onPrepared(MediaPlayer mp) {
        mp.setScreenOnWhilePlaying(true);
    }
});

四、播放完成後的行為。VideoView 播完預設停在最後一幀,若要重播或跳下一個,需搭配 setOnCompletionListener()。

五、不支援的格式要處理。VideoView 底層是 MediaPlayer,對 MKV、部分 HEVC 編碼支援有限。建議在 setOnErrorListener() 中回傳 true 以自行處理錯誤,避免弹出系統的錯誤對話框。

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