Android SurfaceView实现全屏播放例子

  public class Mymedia extends Activity implements
      OnBufferingUpdateListener,
      OnCompletionListener,
      MediaPlayer.OnPreparedListener,
      SurfaceHolder.Callback
{
private static final String TAG = "Mymedia ";
private int     mVideoWidth;
private int     mVideoHeight;
private MediaPlayer   mMediaPlayer;
private SurfaceView   mPreview;
private SurfaceHolder  holder;
private String    path;
public void onCreate(Bundle icicle)
{
  super.onCreate(icicle);
  setContentView(R.layout.main);
  mPreview = (SurfaceView) findViewById(R.id.surface);
  /* 得到SurfaceHolder对象 */
  holder = mPreview.getHolder();
  /* 设置回调函数 */
  holder.addCallback(this);
  /* 设置风格 */
  holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
private void playVideo()
{
  try
  {
   path = "http://www.dubblogs.cc:8751/android/Test/Media/3gp/test.3gp";
   //path = "/sdcard/test.3gp";
   /* 构建MediaPlayer对象 */
   mMediaPlayer = new MediaPlayer();
   /* 设置媒体文件路径 */
   mMediaPlayer.setDataSource(path);
   /* 设置通过SurfaceView来显示画面 */
   mMediaPlayer.setDisplay(holder);
   /* 准备 */
   mMediaPlayer.prepare();
   /* 设置事件监听 */
   mMediaPlayer.setOnBufferingUpdateListener(this);
   mMediaPlayer.setOnCompletionListener(this);
   mMediaPlayer.setOnPreparedListener(this);
   mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
  }
  catch (Exception e)
  {
   Log.e(TAG, "error: " + e.getMessage(), e);
  }
}
public void onBufferingUpdate(MediaPlayer arg0, int percent)
{
  Log.v(TAG, "onBufferingUpdate percent:" + percent);
}
public void onCompletion(MediaPlayer arg0)
{
  Log.v(TAG, "onCompletion called");
}
public void onPrepared(MediaPlayer mediaplayer)
{
  Log.v(TAG, "onPrepared called");
  mVideoWidth = mMediaPlayer.getVideoWidth();
  mVideoHeight = mMediaPlayer.getVideoHeight();
  if (mVideoWidth != 0 && mVideoHeight != 0)
  {
   /* 设置视频的宽度和高度 */
   holder.setFixedSize(mVideoWidth, mVideoHeight);
   /* 开始播放 */
   mMediaPlayer.start();
  }
}
/* 更改时出发的事件 */
public void surfaceChanged(SurfaceHolder surfaceholder, int i, int j, int k)
{
  Log.v(TAG, "surfaceChanged called");
}
/* 销毁 */
public void surfaceDestroyed(SurfaceHolder surfaceholder)
{
  Log.v(TAG, "surfaceDestroyed called");
}
/* 当SurfaceHolder创建时触发 */
public void surfaceCreated(SurfaceHolder holder)
{
  Log.v(TAG, "surfaceCreated called");
  playVideo();
}
/* 销毁 */
@Override
protected void onDestroy()
{
  super.onDestroy();
  if (mMediaPlayer != null)
  {
   mMediaPlayer.release();
   mMediaPlayer = null;
  }
}
}
主要是这段哈:
public void onPrepared(MediaPlayer mediaplayer)
{
  Log.v(TAG, "onPrepared called");
  mVideoWidth = mMediaPlayer.getVideoWidth();
  mVideoHeight = mMediaPlayer.getVideoHeight();
  if (mVideoWidth != 0 && mVideoHeight != 0)
  {
   /* 设置视频的宽度和高度 */
   holder.setFixedSize(mVideoWidth, mVideoHeight);
   /* 开始播放 */
   mMediaPlayer.start();
  }
}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。