主要逻辑:将assets内视频先复制到本地存储,然后通过本地地址进行播放,直接复制文档中代码就可以看到效果
- 新建videoView控件
2.在main文件夹内新建assets文件夹,并将我们需要的视频文件放入,见下图
3,修改MainActivity内逻辑代码如下
package io.com.video;
import androidx.appcompat.app.AppCompatActivity;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获得下载目录,不推荐使用,api29已弃用,返回的是公共下载目录,需要声明存储权限
//File directory_doc = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
//获得下载目录,返回的是应用下载目录
String file_path=getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString()+"/video";
Deposit(file_path,"wanjia.mp4");
//使用VideoView播放视频
VideoView videoView = (VideoView)findViewById(R.id.videoView);
String path=file_path+"/wanjia.mp4";
Log.d("播放地址",path);
videoView.setVideoPath(path);
//创建MediaController对象
MediaController mediaController = new MediaController(this);
//绑定mediaController
videoView.setMediaController(mediaController);
videoView.requestFocus();
}
//将assets内文件存储到本地下载目录
public Boolean Deposit(String path,String fileName){
InputStream inputStream;
try {
//判断文件是否存在
File file1=new File(path + "/" + fileName);
if(!file1.exists()){
inputStream=getAssets().open(fileName);
File file = new File(path);
//当目录不存在时创建目录
if(!file.exists()){
file.mkdirs();
}
FileOutputStream fileOutputStream = new FileOutputStream(path + "/" + fileName);// 保存到本地的文件夹下的文件
byte[] buffer = new byte[1024];
int count = 0;
while ((count = inputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, count);
}
fileOutputStream.flush();
fileOutputStream.close();
inputStream.close();
}else {
Toast.makeText(MainActivity.this,"已存在",Toast.LENGTH_LONG).show();
}
return true;
}catch (IOException e){
e.printStackTrace();
}
return false;
}
}
4,最终效果