Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 進階開發

用 VideoView 實作 Android 影片播放功能

編輯:進階開發

先前我們談過錄音與錄影的實作,這次來看播放。Android 內建的 VideoView 幾乎把播放器的髒活都包好了,只要指定影片路徑再叫 start() 就能跑起來。

Activity 程式碼

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.VideoView;

public class VideoPlayer extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);

        final VideoView w = (VideoView) findViewById(R.id.vdoplayer);

        Button cmdload = (Button) this.findViewById(R.id.cmd_load);
        cmdload.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                w.setVideoPath("/sdcard/android/kongfu.mp4");
            }
        });

        Button cmdplay = (Button) this.findViewById(R.id.cmd_play);
        cmdplay.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                w.start();
            }
        });

        Button cmdpause = (Button) this.findViewById(R.id.cmd_pause);
        cmdpause.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                w.pause();
            }
        });
    }
}

版面配置 main.xml

<?XML version="1.0" encoding="utf-8"?>
<LinearLayout XMLns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <Button android:id="@+id/cmd_load"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="load" />

    <Button android:id="@+id/cmd_play"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Play" />

    <Button android:id="@+id/cmd_pause"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="pause" />

    <VideoView android:id="@+id/vdoplayer"
        android:layout_width="fill_parent"
        android:layout_height="300px" />

</LinearLayout>

幾個實作提醒

三個按鈕分別負責載入、播放與暫停,邏輯非常直白。實務上有兩點要留意:一是寫死的路徑(這裡是 /sdcard/android/kongfu.mp4)在正式版本中應改為動態選擇;二是 VideoView 的尺寸最好別用 px,改用 dip 或 match_parent 之類的單位,換到不同解析度的裝置上才不會跑掉。

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