首先附上kotlin代码:循环播放
views.adsVideo.setVideoPath(Uri.parse(entity.data.video).toString())
views.adsVideo.start()
views.adsVideo.requestFocus()
views.adsVideo.setOnErrorListener(MediaPlayer.OnErrorListener { _, _, _ ->
views.adsVideo.stopPlayback() //播放异常,则停止播放,防止弹窗使界面阻塞
true
})
views.adsVideo.setOnCompletionListener(MediaPlayer.OnCompletionListener { mPlayer ->
mPlayer.start()
mPlayer.setLooping(true)
}
)
问题出现:播放的时候,直接展示在顶部,尝试了一下,修改高度,原因是heightMeasureSpec应该是从顶部算的,然后减去getHeight(),完美展示
public class CustomVideoView extends VideoView {
public CustomVideoView(Context context) {
this(context, null);
}
public CustomVideoView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomVideoView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = getDefaultSize(getWidth(), widthMeasureSpec);
//修改在这
int height = getDefaultSize(getHeight(), heightMeasureSpec-getHeight());
setMeasuredDimension(width, height);
}
}
循环播放
views.adsVideo.setOnCompletionListener(MediaPlayer.OnCompletionListener { mPlayer ->
mPlayer.start()
mPlayer.isLooping=true
}
)
//播放异常,则停止播放,防止弹窗使界面阻塞
views.adsVideo.setOnErrorListener(MediaPlayer.OnErrorListener { _, _, _ ->
views.adsVideo.stopPlayback() //播放异常,则停止播放,防止弹窗使界面阻塞
views.videoLayout.isVisible = false
views.adsBaner.isVisible = true
true
})
默认有声播放,获取 mediaPlayer
private var slience: Boolean = false
private var mediaPlayer: MediaPlayer? = null
views.adsVideo.setOnPreparedListener(MediaPlayer.OnPreparedListener { mp ->
mediaPlayer = mp
mp.setVolume(1f, 1f)
})
点击按钮进行切换
views.btVoice.setOnClickListener {
if (mediaPlayer != null) {
if (!slience) {
mediaPlayer?.setVolume(0f, 0f) //静音
} else {
mediaPlayer?.setVolume(1f, 1f) //有声
}
slience = !slience
if (slience) {
views.btVoice.setImageResource(R.drawable.ic_video_close)
} else {
views.btVoice.setImageResource(R.drawable.ic_video_open)
}
}
}
当用户在播放视频的时候切换到页面,再次切换回来的时候VideoView会销毁,
应该在切换的时候停止播放记,录当前的播放位置,再次切换回来的时候继续播放。
// 视频播放的位置
private int mVideoCurrantPosition = 0;
override fun onResume() {
super.onResume()
if(videoUrl!=null){
//再次打开继续播放视频
views.adsVideo.seekTo(mVideoCurrantPosition)
views.adsVideo.start()
}
}
override fun onPause() {
super.onPause()
if(videoUrl!=null){
//在视频播放过程中切换页面停止播放视频,记录下当前播放位置
mVideoCurrantPosition = views.adsVideo.currentPosition
views.adsVideo.pause()
}
}
网友评论