VideoView是安卓自带的视频播放控件,可以通过两种方式播放,一种是访问网络,还有一种是访问本地视频
第一种:访问网络
代码:
package com.example.day08;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;
public class VideoActivity extends AppCompatActivity implements View.OnClickListener {
VideoView videoView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
init();
}
private void init() {
videoView = findViewById(R.id.videoview);
//按钮监听事件
findViewById(R.id.play).setOnClickListener(this);
findViewById(R.id.pause_1).setOnClickListener(this);
findViewById(R.id.stop_1).setOnClickListener(this);
videoView.setMediaController(new MediaController(this));//获得控制器
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.play:
Uri uri = Uri.parse("https://media.w3.org/2010/05/sintel/trailer.mp4");
videoView.setVideoURI(uri);//设置播放哪个资源
videoView.requestFocus();
videoView.start();
Toast.makeText(this, "播放", Toast.LENGTH_SHORT).show();
break;
case R.id.pause_1:
videoView.pause();
Toast.makeText(this, "暂停", Toast.LENGTH_SHORT).show();
break;
case R.id.stop_1:
videoView.stopPlayback();
videoView.resume();
Toast.makeText(this, "停止", Toast.LENGTH_SHORT).show();
break;
}
}
}
此控件自带暂停与快进
第二种:访问本地
package com.example.day08;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;
public class VideoActivity extends AppCompatActivity implements View.OnClickListener {
VideoView videoView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
init();
}
private void init() {
videoView = findViewById(R.id.videoview);
//按钮监听事件
findViewById(R.id.play).setOnClickListener(this);
findViewById(R.id.pause_1).setOnClickListener(this);
findViewById(R.id.stop_1).setOnClickListener(this);
videoView.setMediaController(new MediaController(this));//获得控制器
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.play:
//去获取本地路径
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
videoView.setVideoPath(path);//将路径设置给资源
videoView.requestFocus();
videoView.start();
Toast.makeText(this, "播放", Toast.LENGTH_SHORT).show();
break;
case R.id.pause_1:
videoView.pause();
Toast.makeText(this, "暂停", Toast.LENGTH_SHORT).show();
break;
case R.id.stop_1:
videoView.stopPlayback();
videoView.resume();
Toast.makeText(this, "停止", Toast.LENGTH_SHORT).show();
break;
}
}
}