本文共 2211 字,大约阅读时间需要 7 分钟。
public classMymedia extends Activity implements
OnBufferingUpdateListener,
OnCompletionListener,
MediaPlayer.OnPreparedListener,
SurfaceHolder.Callback
{private static final String TAG = "Mymedia";private intmVideoWidth;private intmVideoHeight;privateMediaPlayer mMediaPlayer;privateSurfaceView mPreview;privateSurfaceHolder holder;privateString path;public voidonCreate(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 voidplayVideo()
{try{
path= "http://www.dubblogs.cc:8751/android/Test/Media/3gp/test.3gp";//path = "/sdcard/test.3gp";
/*构建MediaPlayer对象*/mMediaPlayer= newMediaPlayer();/*设置媒体文件路径*/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, intpercent)
{
Log.v(TAG,"onBufferingUpdate percent:" +percent);
}public voidonCompletion(MediaPlayer arg0)
{
Log.v(TAG,"onCompletion called");
}public voidonPrepared(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, intk)
{
Log.v(TAG,"surfaceChanged called");
}/*销毁*/
public voidsurfaceDestroyed(SurfaceHolder surfaceholder)
{
Log.v(TAG,"surfaceDestroyed called");
}/*当SurfaceHolder创建时触发*/
public voidsurfaceCreated(SurfaceHolder holder)
{
Log.v(TAG,"surfaceCreated called");
playVideo();
}/*销毁*/@Overrideprotected voidonDestroy()
{
super.onDestroy();if (mMediaPlayer != null)
{
mMediaPlayer.release();
mMediaPlayer= null;
}
}
}
转载地址:http://xmiox.baihongyu.com/