SurfaceView+MediaPlayer实现视频播放
Posted zhangjin1120
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SurfaceView+MediaPlayer实现视频播放相关的知识,希望对你有一定的参考价值。
效果图,是动画片《辛特尔》的截图,加载可能要几十秒
- 不要忘了网络权限
<uses-permission android:name="android.permission.INTERNET" />
- MainActivity.java代码
public class MainActivity extends AppCompatActivity
private SurfaceView surfaceView;
private MediaPlayer player;
private SurfaceHolder holder;
private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
String uri = "https://media.w3.org/2010/05/sintel/trailer.mp4";
player = new MediaPlayer();
try
player.setDataSource(this, Uri.parse(uri));
holder = surfaceView.getHolder();
holder.addCallback(new MyCallBack());
player.prepareAsync();
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
@Override
public void onPrepared(MediaPlayer mp)
progressBar.setVisibility(View.INVISIBLE);
player.start();
player.setLooping(true);
);
catch (IOException e)
e.printStackTrace();
private class MyCallBack implements SurfaceHolder.Callback
@Override
public void surfaceCreated(SurfaceHolder holder)
player.setDisplay(holder);
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
@Override
public void surfaceDestroyed(SurfaceHolder holder)
activity_main.xml
布局代码
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<SurfaceView
android:id="@+id/surfaceView"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_centerInParent="true"
/>
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
/>
</RelativeLayout>
以上是关于SurfaceView+MediaPlayer实现视频播放的主要内容,如果未能解决你的问题,请参考以下文章
SurfaceViewVideoList 列表视频(SurfaceView+Mediaplayer实现播放功能 本地)
Android MediaPlayer+SurfaceView播放视频(附Demo)