布局中使用了TextureView来进行视屏播放:
<TextureView
android:id="@+id/texture_view"
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:layout_height="match_parent"/>
Avtivity逻辑代码:
private MediaPlayer mMediaPlayer;
@BindView(texture_view)
public TextureView texture_view;
......调用如下方法
private void playVideo(String videoPath){
if(mMediaPlayer != null){
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
}
try {
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(videoPath);
mMediaPlayer.setSurface(new Surface(texture_view.getSurfaceTexture()));
mMediaPlayer.setLooping(true);
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mp.start();
float ratio = mp.getVideoWidth()*1f/mp.getVideoHeight();
int width = texture_view.getWidth();
int height = texture_view.getHeight();
ViewGroup.LayoutParams layoutParams = texture_view.getLayoutParams();
layoutParams.width = (int) (height*ratio);
texture_view.setLayoutParams(layoutParams);
}
});
mMediaPlayer.prepareAsync();
}catch (Exception e){
e.printStackTrace();
}
}
这样运行便或出现题目中所示的错误,不会崩溃,只是资源视频无法显示,为此,进行如下修改。
private Surface surface;
texture_view.setSurfaceTextureListener(this);
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
surface=new Surface(surfaceTexture);
playVideo(actionVideoPath);
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int width, int height) {
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
surfaceTexture=null;
surface=null;
mMediaPlayer.stop();
mMediaPlayer.release();
return true;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
}
|