android:自己实现能播放网络视频url的播放器

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

android原生自带的播放器一般只能播放本地视频,而没有播放url的功能。不过android系统中有一个VideoView的控件可以实现这一功能。

简单实现如下:

public class MyVideoPlay extends Activity implements MediaPlayer.OnErrorListener,
        MediaPlayer.OnCompletionListener {
    public static final String TAG = "MyVideoPlay";
    private VideoView mVideoView;
    private Uri mUri;
    private int mPositionWhenPaused = -1;
 
    private MediaController mMediaController;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        setContentView(R.layout.video_view);
 
        //Set the screen to landscape.
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
 
        mVideoView = (VideoView)findViewById(R.id.my_video_view);
 
        //Video file
        Intent it = getIntent();
        mUri = Uri.parse(it.getStringExtra("netUrl"));
 
        //Create media controller
        mMediaController = new MediaController(this);
        mVideoView.setMediaController(mMediaController);
        mVideoView.setOnCompletionListener(new OnCompletionListener() {			
			@Override
			public void onCompletion(MediaPlayer mp) {
				// TODO Auto-generated method stub
				MyVideoPlay.this.finish();
			}
		});
    }
 
    public void onStart() {
        // Play Video
    	if (mVideoView != null && mUri != null) {
	        mVideoView.setVideoURI(mUri);
	        mVideoView.start();
    	} else {
    		Toast.makeText(MyVideoPlay.this, "发生错误", Toast.LENGTH_SHORT).show();
    	}
        super.onStart();
    }
 
    public void onPause() {
        mPositionWhenPaused = mVideoView.getCurrentPosition();
        mVideoView.stopPlayback();       
        super.onPause();
    }
 
    public void onResume() {
        // Resume video player
        if(mPositionWhenPaused >= 0) {
            mVideoView.seekTo(mPositionWhenPaused);
            mPositionWhenPaused = -1;
        }
 
        super.onResume();
    }
 
    public boolean onError(MediaPlayer player, int arg1, int arg2) {
        return false;
    }
 
    public void onCompletion(MediaPlayer mp) {
    	MyVideoPlay.this.finish();
    }
}

 截图:

android:自己实现能播放网络视频url的播放器_第1张图片

 

转载于:https://my.oschina.net/nicksong/blog/149264

你可能感兴趣的:(android:自己实现能播放网络视频url的播放器)