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

從零開始學 Android:用 MediaPlayer 播放影片

編輯:Android 技術基礎

Android 播放影片的三種常見做法

  1. 呼叫系統播放器:使用 ACTION_VIEW、Uri 與 MIME 類型。
  2. 使用 VideoView 搭配 MediaController。
  3. 使用 MediaPlayer 與 SurfaceView,自由度最高。

本篇以第三種為主。MediaPlayer 負責解碼與播放,SurfaceView 提供畫面顯示的 Surface,兩者搭配即可完成自訂播放器。

介面設計

先將 play.png 與 stop.png 複製到 res/drawable-hdpi。

布局中放入兩個 ImageButton 與一個 SurfaceView。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageButton
        android:id="@+id/playvideo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/play" />

    <ImageButton
        android:id="@+id/stopvideo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/stop" />

    <SurfaceView
        android:id="@+id/surface"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

程式實作

MainActivity 取得 SurfaceView 與 SurfaceHolder,建立 MediaPlayer,指定影片路徑。播放時設定音訊串流型態與顯示表面,再 prepare 與 start。

surfaceHolder = surfaceView.getHolder();
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

media = new MediaPlayer();
media.setDataSource(
    Environment.getExternalStorageDirectory().getPath()
    + "/genwoxue/mybaby.3gp");
media.setAudioStreamType(AudioManager.STREAM_MUSIC);
media.setDisplay(surfaceHolder);
media.prepare();
media.start();

停止播放:

media.stop();

執行結果

按下播放後,影片會顯示在 SurfaceView 上。

補充:另外兩種播放方式

若只是快速播放,可直接用系統 Intent:

Uri uri = Uri.parse(
    Environment.getExternalStorageDirectory().getPath()
    + "/Test_Movie.m4v");

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "video/mp4");
startActivity(intent);

或使用 VideoView:

VideoView videoView = findViewById(R.id.video_view);
videoView.setMediaController(new MediaController(this));
videoView.setVideoURI(uri);
videoView.start();
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved