package com.example.mytest.ui.launch;
import android.content.Context;
import android.media.AudioAttributes;
import android.media.AudioFocusRequest;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.MediaController;
import androidx.annotation.NonNull;
import java.io.IOException;
import java.util.Map;
/**
* 启动页视频播放器
*/
public class LauncherMediaPlayer extends SurfaceView implements MediaController.MediaPlayerControl {
private static final String TAG = "LauncherMediaPlayer";
private static final int STATE_ERROR = -1;
private static final int STATE_IDLE = 0;
private static final int STATE_PREPARING = 1;
private static final int STATE_PREPARED = 2;
private static final int STATE_PLAYING = 3;
private static final int STATE_PAUSED = 4;
private static final int STATE_PLAYBACK_COMPLETED = 5;
private final Context mContext;
private final AudioManager mAudioManager;
private int mVideoWidth, mVideoHeight, mSurfaceWidth, mSurfaceHeight;
private int mAudioFocusType = AudioManager.AUDIOFOCUS_NONE;
private MediaPlayer mMediaPlayer;
private SurfaceHolder mSurfaceHolder;
private MediaController mMediaController;
private AudioAttributes mAudioAttributes;
private Uri mUri;
private int mCurrentState = STATE_IDLE;
private int mTargetState = STATE_IDLE;
private int mCurrentBufferPercentage;
private int mSeekWhenPrepared;
public LauncherMediaPlayer(Context context) {
this(context, null);
}
public LauncherMediaPlayer(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public LauncherMediaPlayer(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mContext = context;
mVideoWidth = 0;
mVideoHeight = 0;
mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
mAudioAttributes = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MOVIE).build();
getHolder().addCallback(mSHCallback);
getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
setFocusable(true);
setFocusableInTouchMode(true);
requestFocus();
mCurrentState = STATE_IDLE;
mTargetState = STATE_IDLE;
}
public void resume() {
openVideo();
}
public void setVideoPath(String path) {
setVideoURI(Uri.parse(path));
}
public void setVideoURI(Uri uri) {
setVideoURI(uri, null);
}
public void setVideoURI(Uri uri, Map<String, String> headers) {
mUri = uri;
mSeekWhenPrepared = 0;
openVideo();
requestLayout();
invalidate();
}
private void openVideo() {
if (mUri == null || mSurfaceHolder == null) {
// not ready for playback just yet, will try again later
return;
}
// we shouldn't clear the target state, because somebody might have
// called start() previously
release(false);
if (mAudioFocusType != AudioManager.AUDIOFOCUS_NONE) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
AudioFocusRequest request = new AudioFocusRequest.Builder(mAudioFocusType).build();
mAudioManager.requestAudioFocus(request);
} else {
mAudioManager.requestAudioFocus(null, mAudioFocusType, 0 /*flags*/);
}
}
try {
MediaPlayer tmpMp = mMediaPlayer = new MediaPlayer();
final Context context = getContext();
if (mAudioSession != 0) {
tmpMp.setAudioSessionId(mAudioSession);
} else {
mAudioSession = tmpMp.getAudioSessionId();
}
tmpMp.setOnPreparedListener(mPreparedListener);
tmpMp.setOnVideoSizeChangedListener(mSizeChangedListener);
tmpMp.setOnCompletionListener(mCompletionListener);
tmpMp.setOnErrorListener(mErrorListener);
// tmpMp.setOnInfoListener(mInfoListener);
tmpMp.setOnBufferingUpdateListener(mBufferingUpdateListener);
mCurrentBufferPercentage = 0;
tmpMp.setDataSource(mContext, mUri);
tmpMp.setDisplay(mSurfaceHolder);
tmpMp.setAudioAttributes(mAudioAttributes);
// tmpMp.setVolume(0f, 0f);
tmpMp.setScreenOnWhilePlaying(true);
tmpMp.prepareAsync();
// we don't set the target state here either, but preserve the
// target state that was there before.
mCurrentState = STATE_PREPARING;
attachMediaController();
} catch (IOException ex) {
Log.w(TAG, "Unable to open content: " + mUri, ex);
mCurrentState = STATE_ERROR;
mTargetState = STATE_ERROR;
mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
return;
} catch (IllegalArgumentException ex) {
Log.w(TAG, "Unable to open content: " + mUri, ex);
mCurrentState = STATE_ERROR;
mTargetState = STATE_ERROR;
mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
return;
}
}
private void attachMediaController() {
if (mMediaPlayer != null && mMediaController != null) {
mMediaController.setMediaPlayer(this);
View anchorView = this.getParent() instanceof View ?
(View) this.getParent() : this;
mMediaController.setAnchorView(anchorView);
mMediaController.setEnabled(isInPlaybackState());
}
}
@Override
public boolean isPlaying() {
return isInPlaybackState() && mMediaPlayer.isPlaying();
}
private boolean isInPlaybackState() {
return (mMediaPlayer != null &&
mCurrentState != STATE_ERROR &&
mCurrentState != STATE_IDLE &&
mCurrentState != STATE_PREPARING);
}
@Override
public void start() {
if (isInPlaybackState()) {
mMediaPlayer.start();
mCurrentState = STATE_PLAYING;
}
mTargetState = STATE_PLAYING;
}
@Override
public void pause() {
if (isInPlaybackState()) {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
mCurrentState = STATE_PAUSED;
}
}
mTargetState = STATE_PAUSED;
}
private void release(boolean clearTargetState) {
if (mMediaPlayer != null) {
mMediaPlayer.reset();
mMediaPlayer.release();
mMediaPlayer = null;
mCurrentState = STATE_IDLE;
if (clearTargetState) {
mTargetState = STATE_IDLE;
}
if (mAudioFocusType != AudioManager.AUDIOFOCUS_NONE) {
mAudioManager.abandonAudioFocus(null);
}
}
}
private SurfaceHolder.Callback mSHCallback = new SurfaceHolder.Callback() {
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
mSurfaceWidth = w;
mSurfaceHeight = h;
boolean isValidState = (mTargetState == STATE_PLAYING);
boolean hasValidSize = (mVideoWidth == w && mVideoHeight == h);
if (mMediaPlayer != null && isValidState && hasValidSize) {
if (mSeekWhenPrepared != 0) {
seekTo(mSeekWhenPrepared);
}
start();
}
}
public void surfaceCreated(SurfaceHolder holder) {
mSurfaceHolder = holder;
openVideo();
}
public void surfaceDestroyed(SurfaceHolder holder) {
// after we return from this we can't use the surface any more
mSurfaceHolder = null;
if (mMediaController != null) mMediaController.hide();
release(true);
}
};
private final MediaPlayer.OnBufferingUpdateListener mBufferingUpdateListener =
new MediaPlayer.OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
mCurrentBufferPercentage = percent;
}
};
private final MediaPlayer.OnPreparedListener mPreparedListener = new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mCurrentState = STATE_PREPARED;
if (mListener != null) {
mListener.onPrepared(mMediaPlayer);
}
float videoRatio = mp.getVideoWidth() / (float) mp.getVideoHeight();
float screenRatio = mSurfaceWidth / (float) mSurfaceHeight;
float scaleX = videoRatio / screenRatio;
if (scaleX >= 1f) {
setScaleX(scaleX);
} else {
setScaleY(1f / scaleX);
}
if (mMediaController != null) {
mMediaController.setEnabled(true);
}
mVideoWidth = mp.getVideoWidth();
mVideoHeight = mp.getVideoHeight();
int seekToPosition = mSeekWhenPrepared; // mSeekWhenPrepared may be changed after seekTo() call
if (seekToPosition != 0) {
seekTo(seekToPosition);
}
if (mVideoWidth != 0 && mVideoHeight != 0) {
Log.i(TAG, "video size: " + mVideoWidth + "/" + mVideoHeight);
getHolder().setFixedSize(mVideoWidth, mVideoHeight);
if (mSurfaceWidth == mVideoWidth && mSurfaceHeight == mVideoHeight) {
// We didn't actually change the size (it was already at the size
// we need), so we won't get a "surface changed" callback, so
// start the video here instead of in the callback.
if (mTargetState == STATE_PLAYING) {
start();
if (mMediaController != null) {
mMediaController.show();
}
} else if (!isPlaying() &&
(seekToPosition != 0 || getCurrentPosition() > 0)) {
if (mMediaController != null) {
// Show the media controls when we're paused into a video and make 'em stick.
mMediaController.show(0);
}
}
}
} else {
// We don't know the video size yet, but should start anyway.
// The video size might be reported to us later.
if (mTargetState == STATE_PLAYING) {
start();
}
}
}
};
private final MediaPlayer.OnVideoSizeChangedListener mSizeChangedListener =
new MediaPlayer.OnVideoSizeChangedListener() {
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
mVideoWidth = mp.getVideoWidth();
mVideoHeight = mp.getVideoHeight();
if (mVideoWidth != 0 && mVideoHeight != 0) {
getHolder().setFixedSize(mVideoWidth, mVideoHeight);
requestLayout();
}
}
};
private final MediaPlayer.OnCompletionListener mCompletionListener =
new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mCurrentState = STATE_PLAYBACK_COMPLETED;
mTargetState = STATE_PLAYBACK_COMPLETED;
if (mMediaController != null) {
mMediaController.hide();
}
if (mListener != null) {
mListener.onCompletion(mMediaPlayer);
}
if (mAudioFocusType != AudioManager.AUDIOFOCUS_NONE) {
mAudioManager.abandonAudioFocus(null);
}
}
};
private final MediaPlayer.OnErrorListener mErrorListener =
new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int framework_err, int impl_err) {
Log.d(TAG, "Error: " + framework_err + "," + impl_err);
mCurrentState = STATE_ERROR;
mTargetState = STATE_ERROR;
if (mMediaController != null) {
mMediaController.hide();
}
/* If an error handler has been supplied, use it and finish. */
if (mListener != null) {
if (mListener.onError(mMediaPlayer, framework_err, impl_err)) {
return true;
}
}
return true;
}
};
public void setAudioFocusRequest(int focusGain) {
if (focusGain != AudioManager.AUDIOFOCUS_NONE
&& focusGain != AudioManager.AUDIOFOCUS_GAIN
&& focusGain != AudioManager.AUDIOFOCUS_GAIN_TRANSIENT
&& focusGain != AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK
&& focusGain != AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE) {
throw new IllegalArgumentException("Illegal audio focus type " + focusGain);
}
mAudioFocusType = focusGain;
}
@Override
public int getDuration() {
if (isInPlaybackState()) {
return mMediaPlayer.getDuration();
}
return -1;
}
@Override
public int getCurrentPosition() {
if (isInPlaybackState()) {
return mMediaPlayer.getCurrentPosition();
}
return 0;
}
@Override
public void seekTo(int msec) {
if (isInPlaybackState()) {
mMediaPlayer.seekTo(msec);
mSeekWhenPrepared = 0;
} else {
mSeekWhenPrepared = msec;
}
}
@Override
public int getBufferPercentage() {
return mCurrentBufferPercentage;
}
@Override
public boolean canPause() {
return false;
}
@Override
public boolean canSeekBackward() {
return false;
}
@Override
public boolean canSeekForward() {
return false;
}
private int mAudioSession;
@Override
public int getAudioSessionId() {
if (mAudioSession == 0) {
MediaPlayer foo = new MediaPlayer();
mAudioSession = foo.getAudioSessionId();
foo.release();
}
return mAudioSession;
}
private PlayListener mListener;
public void setPlayListener(PlayListener l) {
mListener = l;
}
public interface PlayListener {
void onPrepared(@NonNull MediaPlayer player);
boolean onError(@NonNull MediaPlayer player, int frameworkErr, int implErr);
void onCompletion(@NonNull MediaPlayer player);
}
}
网友评论