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

用VideoView輕鬆實現Android視頻播放全解析

編輯:關於 Android 程式設計

在Android中透過VideoView播放視頻,大致可以拆成三個步驟:

1、在佈局檔中定義VideoView組件,或者在程式碼中動態創建VideoView組件;

2、呼叫VideoView的以下兩個方法之一來加載指定視頻:

(1)setVideoPath(String path):加載path檔案所代表的視頻;

(2)setVideoURI(Uri uri):加載uri所對應的視頻。

3、呼叫VideoView的start()、stop()、pause()方法來控制視頻的播放。

更省事的是,VideoView只要與MediaController類結合使用,開發者就不必自己費心控制播放與暫停了。下面是完整範例:

 package cn.com.chenzheng_java; import android.app.Activity; import android.media.MediaPlayer; import android.os.Bundle; import android.util.Log; import android.widget.MediaController; import android.widget.VideoView; import android.widget.MediaController.MediaPlayerControl; public class VideoActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.video); VideoView videoView = (VideoView)findViewById(R.id.videoView1); /*** * 將播放器關聯上一個音頻或者視頻文件 * videoView.setVideoURI(Uri uri) * videoView.setVideoPath(String path) * 以上兩個方法都可以。 */ videoView.setVideoPath("data/yueding.mp3"); /** * w為其提供一個控制器,控制其暫停、播放……等功能 */ videoView.setMediaController(new MediaController(this)); /** * 視頻或者音頻到結尾時觸發的方法 */ videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { Log.i("通知", "完成"); } }); videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() { @Override public boolean onError(MediaPlayer mp, int what, int extra) { Log.i("通知", "播放中出現錯誤"); return false; } }); } } 

對應的video.xml佈局檔:

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <VideoView android:layout_height="match_parent" android:id="@+id/videoView1" android:layout_width="wrap_content"></VideoView> </LinearLayout> 

值得一提的是,我們同樣可以用它來播放網路上的多媒體資源,只要把setVideoPath換成合適的網路URI即可。

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