今天来说一下Android中怎么实现视频播放,我主要说三种:
1.MediaPlayer+SurfaceView;
2.VideoView;
3.Vitamio框架。
1.MediaPlayer+SurfaceView这种方法是基础,后面的两种方法其实就是把这种方法封装了一下,使用起来更方便些。
我认为大家基本都会用MediaPlayer这个API,我们都知道MediaPlayer是媒体播放器,可以播放音频,视频其实就是给音频配上影像,而SurfaceView就是给音频配上影像的工具,我们只需要把SurfaceView与MediaPlayer关联起来就行了。
主要代码:
SurfaceHolder holder = SurfaceView.getHolder();
MediaPlayer.setDisplay(holder);//将影像播放控件与媒体播放控件关联起来我认为之前不知道的代码可能只有这两句。
布局代码:
效果图
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.video.MainActivity" android:layout_margin="10dp" android:orientation="vertical"> <EditText android:id="@+id/et" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入文件名称例如:aa.mp4,务必确保文件放在sdcard目录下"/> <SurfaceView android:id="@+id/sfv" android:layout_width="match_parent" android:layout_marginTop="10dp" android:layout_height="200dp" /> <SeekBar android:id="@+id/sb" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp"/> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:orientation="horizontal"> <Button android:id="@+id/play" android:layout_width="0dp" android:layout_height="60dp" android:layout_weight="1" android:onClick="play" android:text="播放"/> <Button android:id="@+id/pause" android:layout_width="0dp" android:layout_height="60dp" android:layout_marginLeft="10dp" android:layout_weight="1" android:onClick="pause" android:text="暂停"/> <Button android:layout_width="0dp" android:layout_height="60dp" android:layout_marginLeft="10dp" android:layout_weight="1" android:onClick="stop" android:text="停止"/> <Button android:layout_width="0dp" android