Android VideoView播放本地视频短暂黑屏的解决方法

https://blog.csdn.net/goodlixueyong/article/details/53590573

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.widget.VideoView;

import java.io.File;

public class VideoManager {
    private VideoView mVideoView;
    private MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();

    @SuppressLint("CheckResult")
    public VideoManager(VideoView videoView) {
        mVideoView = videoView;
        // 设置准备完成监听
        mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                // 准备完成后开始播放
                mp.start();
            }
        });
        // 设置播放信息监听
        mVideoView.setOnInfoListener(new MediaPlayer.OnInfoListener() {
            @Override
            public boolean onInfo(MediaPlayer mp, int what, int extra) {
                // 视频帧开始渲染时设置背景透明
                if (what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) {
                    mVideoView.setBackgroundColor(Color.TRANSPARENT);
                }
                return true;
            }
        });
    }

    /**
     * 播放视频
     */
    public void play(String path) {
        // 设置背景
        setBackground(path);
        // 设置视频地址
        mVideoView.setVideoPath(path);
    }

    /**
     * 设置背景
     */
    private void setBackground(String path) {
        File file = new File(path);
        if (file.exists()) {
            mediaMetadataRetriever.setDataSource(file.getAbsolutePath());
            Bitmap bitmap = mediaMetadataRetriever.getFrameAtTime(1);
            mVideoView.setBackground(new BitmapDrawable(null, bitmap));
        }
    }
}

发表评论