一、布局文件

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".VideoActivity">
<TextureView
android:id="@+id/textureViewVideo"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

<Button
android:id="@+id/btnStartPlay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="开始"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

二、Activity源码

package com.example.learning01;

import androidx.appcompat.app.AppCompatActivity;

import android.hardware.Camera;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;

import java.io.File;
import java.io.IOException;

public class VideoActivity extends AppCompatActivity implements View.OnClickListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener {
private TextureView textureView;
private Button btn;
MediaPlayer mediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);

textureView= findViewById(R.id.textureViewVideo);
btn = findViewById(R.id.btnStartPlay);


btn.setOnClickListener(this);
}

@Override
public void onClick(View view) {
CharSequence text = btn.getText();
if(TextUtils.equals(text,"开始")){
btn.setText("结束");

mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnCompletionListener(this);
try {
mediaPlayer.setDataSource(new File(getExternalFilesDir(""),"video.mp4").getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}

mediaPlayer.setSurface(new Surface(textureView.getSurfaceTexture()));

mediaPlayer.prepareAsync();
}

else {
btn.setText("开始");
mediaPlayer.stop();
mediaPlayer.release();

}
}

@Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
}

@Override
public void onCompletion(MediaPlayer mediaPlayer) {//视频部分完成
btn.setText("开始");
mediaPlayer.stop();
mediaPlayer.release();
}
}

三、注意点

视频播放完记得释放资源哦

public void onCompletion(MediaPlayer mediaPlayer) {//视频部分完成
btn.setText("开始");
mediaPlayer.stop();
mediaPlayer.release();
}