├── .gitignore
├── .idea
├── compiler.xml
├── copyright
│ └── profiles_settings.xml
├── gradle.xml
├── misc.xml
├── modules.xml
├── runConfigurations.xml
└── vcs.xml
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── example
│ │ └── asus
│ │ └── wechatvideoview
│ │ └── ExampleInstrumentedTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── example
│ │ │ └── asus
│ │ │ └── wechatvideoview
│ │ │ ├── MainActivity.java
│ │ │ └── WelcomeActivity.java
│ └── res
│ │ ├── layout
│ │ └── activity_main.xml
│ │ ├── mipmap-hdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-mdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxxhdpi
│ │ └── ic_launcher.png
│ │ ├── values-w820dp
│ │ └── dimens.xml
│ │ └── values
│ │ ├── colors.xml
│ │ ├── dimens.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── com
│ └── example
│ └── asus
│ └── wechatvideoview
│ └── ExampleUnitTest.java
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── wechatsmallvideoview
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
├── androidTest
└── java
│ └── com
│ └── example
│ └── wechatsmallvideoview
│ └── ExampleInstrumentedTest.java
├── main
├── AndroidManifest.xml
├── java
│ └── com
│ │ └── example
│ │ └── wechatsmallvideoview
│ │ ├── LoadingCircleView.java
│ │ ├── SurfaceVideoView.java
│ │ └── SurfaceVideoViewCreator.java
└── res
│ ├── drawable
│ ├── all_darkbackground.xml
│ └── ic_play_24dp.xml
│ ├── layout
│ └── surface_video_view_layout.xml
│ └── values
│ └── strings.xml
└── test
└── java
└── com
└── example
└── wechatsmallvideoview
└── ExampleUnitTest.java
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/workspace.xml
5 | /.idea/libraries
6 | .DS_Store
7 | /build
8 | /captures
9 | .externalNativeBuild
10 |
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
12 |
17 |
22 |
27 |
53 |
55 |
65 |
67 |
76 |
78 |
13 | * author: LinGuanHong. 14 | *
15 | * My GitHub : https://github.com/af913337456/ 16 | *
17 | * My Blog : http://www.cnblogs.com/linguanh/ 18 | *
19 | * on 2017/4/26.
20 | */
21 |
22 | public class WelcomeActivity extends Activity {
23 |
24 |
25 | @Override
26 | protected void onCreate(Bundle savedInstanceState) {
27 | super.onCreate(savedInstanceState);
28 |
29 | LinearLayout linearLayout = new LinearLayout(this);
30 | linearLayout.setVerticalGravity(LinearLayout.HORIZONTAL);
31 |
32 | Button cache = new Button(this);
33 | Button down = new Button(this);
34 |
35 | cache.setText("cache");
36 | down .setText("down");
37 |
38 | linearLayout.addView(cache);
39 | linearLayout.addView(down);
40 |
41 | final Intent intent = new Intent(WelcomeActivity.this,MainActivity.class);
42 | cache.setOnClickListener(new View.OnClickListener() {
43 | @Override
44 | public void onClick(View v) {
45 | intent.putExtra("useCache",true);
46 | startActivity(intent);
47 | }
48 | });
49 |
50 | down.setOnClickListener(new View.OnClickListener() {
51 | @Override
52 | public void onClick(View v) {
53 | intent.putExtra("useCache",false);
54 | startActivity(intent);
55 | }
56 | });
57 |
58 | setContentView(linearLayout);
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
16 | * My GitHub : https://github.com/af913337456/ 17 | *
18 | * My Blog : http://www.cnblogs.com/linguanh/ 19 | *
20 | * second time edited by LinGuanHong on 2017/4/26. 21 | */ 22 | 23 | public class LoadingCircleView extends View { 24 | 25 | 26 | private Paint paintBgCircle; 27 | 28 | 29 | private Paint paintCircle; 30 | 31 | private Paint paintProgressCircle; 32 | 33 | 34 | private float startAngle = -90f;//开始角度 35 | 36 | private float sweepAngle = 0;//结束 37 | 38 | private int progressCirclePadding = 0;//进度圆与背景圆的间距 39 | 40 | 41 | private boolean fillIn = false;//进度圆是否填充 42 | 43 | private int animDuration = 2000; 44 | 45 | 46 | private LodingCircleViewAnim mLodingCircleViewAnim;//动画效果 47 | 48 | 49 | public LoadingCircleView(Context context) { 50 | super(context); 51 | init(); 52 | } 53 | 54 | public LoadingCircleView(Context context, AttributeSet attrs) { 55 | super(context, attrs); 56 | init(); 57 | } 58 | 59 | public LoadingCircleView(Context context, AttributeSet attrs, int defStyleAttr) { 60 | super(context, attrs, defStyleAttr); 61 | init(); 62 | } 63 | 64 | public int dip2px(Context context, float dpValue) { 65 | final float scale = context.getResources().getDisplayMetrics().density; 66 | return (int) (dpValue * scale + 0.5f); 67 | } 68 | 69 | 70 | private void init() { 71 | 72 | mLodingCircleViewAnim = new LodingCircleViewAnim(); 73 | mLodingCircleViewAnim.setDuration(animDuration); 74 | progressCirclePadding = dip2px(getContext(), 3); 75 | 76 | paintBgCircle = new Paint(); 77 | paintBgCircle.setAntiAlias(true); 78 | paintBgCircle.setStyle(Paint.Style.FILL); 79 | paintBgCircle.setColor(Color.WHITE); 80 | 81 | 82 | paintCircle = new Paint(); 83 | paintCircle.setAntiAlias(true); 84 | paintCircle.setStyle(Paint.Style.FILL); 85 | paintCircle.setColor(Color.GRAY); 86 | 87 | 88 | paintProgressCircle = new Paint(); 89 | paintProgressCircle.setAntiAlias(true); 90 | paintProgressCircle.setStyle(Paint.Style.FILL); 91 | paintProgressCircle.setColor(Color.WHITE); 92 | 93 | } 94 | 95 | 96 | @Override 97 | protected void onDraw(Canvas canvas) { 98 | super.onDraw(canvas); 99 | canvas.drawCircle(getMeasuredWidth() / 2, getMeasuredWidth() / 2, getMeasuredWidth() / 2, paintBgCircle); 100 | canvas.drawCircle(getMeasuredWidth() / 2, getMeasuredWidth() / 2, getMeasuredWidth() / 2 - progressCirclePadding / 2, paintCircle); 101 | RectF f = new RectF(progressCirclePadding, progressCirclePadding, getMeasuredWidth() - progressCirclePadding, getMeasuredWidth() - progressCirclePadding); 102 | canvas.drawArc(f, startAngle, sweepAngle, true, paintProgressCircle); 103 | if (!fillIn) 104 | canvas.drawCircle(getMeasuredWidth() / 2, getMeasuredWidth() / 2, getMeasuredWidth() / 2 - progressCirclePadding * 2, paintCircle); 105 | 106 | 107 | } 108 | 109 | 110 | public void startAnimAutomatic(boolean fillIn) { 111 | this.fillIn = fillIn; 112 | if (mLodingCircleViewAnim != null) 113 | clearAnimation(); 114 | startAnimation(mLodingCircleViewAnim); 115 | } 116 | 117 | public void stopAnimAutomatic() { 118 | if (mLodingCircleViewAnim != null) 119 | clearAnimation(); 120 | } 121 | 122 | 123 | public void setProgerss(int progerss, boolean fillIn) { 124 | this.fillIn = fillIn; 125 | sweepAngle = (float) (360 / 100.0 * progerss); 126 | invalidate(); 127 | } 128 | 129 | 130 | private class LodingCircleViewAnim extends Animation { 131 | @Override 132 | protected void applyTransformation(float interpolatedTime, Transformation t) { 133 | super.applyTransformation(interpolatedTime, t); 134 | if (interpolatedTime < 1.0f) { 135 | sweepAngle = 360 * interpolatedTime; 136 | invalidate(); 137 | } else { 138 | startAnimAutomatic(fillIn); 139 | } 140 | 141 | } 142 | } 143 | } -------------------------------------------------------------------------------- /wechatsmallvideoview/src/main/java/com/example/wechatsmallvideoview/SurfaceVideoView.java: -------------------------------------------------------------------------------- 1 | package com.example.wechatsmallvideoview; 2 | 3 | import android.content.Context; 4 | import android.graphics.PixelFormat; 5 | import android.media.AudioManager; 6 | import android.media.MediaPlayer; 7 | import android.media.MediaPlayer.OnInfoListener; 8 | import android.media.MediaPlayer.OnVideoSizeChangedListener; 9 | import android.net.Uri; 10 | import android.os.Build; 11 | import android.os.Handler; 12 | import android.os.Message; 13 | import android.text.TextUtils; 14 | import android.util.AttributeSet; 15 | import android.view.KeyEvent; 16 | import android.view.SurfaceHolder; 17 | import android.view.SurfaceHolder.Callback; 18 | import android.view.SurfaceView; 19 | 20 | import java.io.IOException; 21 | 22 | 23 | /** 24 | * 25 | * My GitHub : https://github.com/af913337456/ 26 | *
27 | * My Blog : http://www.cnblogs.com/linguanh/ 28 | *
29 | * on 2017/4/26. 30 | */ 31 | 32 | public class SurfaceVideoView extends SurfaceView implements Callback { 33 | 34 | /** 定时暂停 */ 35 | private static final int HANDLER_MESSAGE_PARSE = 0; 36 | /** 定时循环 */ 37 | private static final int HANDLER_MESSAGE_LOOP = 1; 38 | 39 | private MediaPlayer.OnCompletionListener mOnCompletionListener; 40 | private MediaPlayer.OnPreparedListener mOnPreparedListener; 41 | private MediaPlayer.OnErrorListener mOnErrorListener; 42 | private MediaPlayer.OnSeekCompleteListener mOnSeekCompleteListener; 43 | private OnInfoListener mOnInfoListener; 44 | private OnVideoSizeChangedListener mOnVideoSizeChangedListener; 45 | private OnPlayStateListener mOnPlayStateListener; 46 | private MediaPlayer mMediaPlayer = null; 47 | private SurfaceHolder mSurfaceHolder = null; 48 | 49 | private MediaPlayer.OnBufferingUpdateListener mOnBufferingUpdateListener; 50 | 51 | private static final int STATE_ERROR = -1; 52 | private static final int STATE_IDLE = 0; 53 | private static final int STATE_PREPARING = 1; 54 | private static final int STATE_PREPARED = 2; 55 | private static final int STATE_PLAYING = 3; 56 | private static final int STATE_PAUSED = 4; 57 | /** 58 | * PlaybackCompleted状态:文件正常播放完毕,而又没有设置循环播放的话就进入该状态, 59 | * 并会触发OnCompletionListener的onCompletion 60 | * ()方法。此时可以调用start()方法重新从头播放文件,也可以stop()停止MediaPlayer,或者也可以seekTo()来重新定位播放位置。 61 | */ 62 | private static final int STATE_PLAYBACK_COMPLETED = 5; 63 | /** Released/End状态:通过release()方法可以进入End状态 */ 64 | private static final int STATE_RELEASED = 5; 65 | 66 | private int mCurrentState = STATE_IDLE; 67 | private int mTargetState = STATE_IDLE; 68 | 69 | private int mVideoWidth; 70 | private int mVideoHeight; 71 | // private int mSurfaceWidth; 72 | // private int mSurfaceHeight; 73 | 74 | // private float mSystemVolumn = -1; 75 | private int mDuration; 76 | private Uri mUri; 77 | 78 | // SurfaceTextureAvailable 79 | 80 | public SurfaceVideoView(Context context, AttributeSet attrs, int defStyle) { 81 | super(context, attrs, defStyle); 82 | initVideoView(); 83 | } 84 | 85 | public SurfaceVideoView(Context context) { 86 | super(context); 87 | initVideoView(); 88 | } 89 | 90 | public SurfaceVideoView(Context context, AttributeSet attrs) { 91 | super(context, attrs); 92 | initVideoView(); 93 | } 94 | 95 | @SuppressWarnings("deprecation") 96 | protected void initVideoView() { 97 | // mTryCount = 0; 98 | mVideoWidth = 0; 99 | mVideoHeight = 0; 100 | 101 | getHolder().setFormat(PixelFormat.RGBA_8888); // PixelFormat.RGB_565 102 | getHolder().addCallback(this); 103 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { 104 | getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); 105 | } 106 | 107 | setFocusable(true); 108 | setFocusableInTouchMode(true); 109 | requestFocus(); 110 | 111 | mCurrentState = STATE_IDLE; 112 | mTargetState = STATE_IDLE; 113 | } 114 | 115 | /** 更新音量 */ 116 | public static float getSystemVolumn(Context context) { 117 | if (context != null) { 118 | try { 119 | AudioManager mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); 120 | int maxVolumn = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC); 121 | return mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC) * 1.0F / maxVolumn; 122 | } catch (UnsupportedOperationException e) { 123 | 124 | } 125 | } 126 | return 0.5F; 127 | } 128 | 129 | public void setOnInfoListener(OnInfoListener l) { 130 | mOnInfoListener = l; 131 | } 132 | 133 | public void setOnVideoSizeChangedListener(OnVideoSizeChangedListener l) { 134 | mOnVideoSizeChangedListener = l; 135 | } 136 | 137 | public void setOnPreparedListener(MediaPlayer.OnPreparedListener l) { 138 | mOnPreparedListener = l; 139 | } 140 | 141 | public void setOnErrorListener(MediaPlayer.OnErrorListener l) { 142 | mOnErrorListener = l; 143 | } 144 | 145 | public void setOnPlayStateListener(OnPlayStateListener l) { 146 | mOnPlayStateListener = l; 147 | } 148 | 149 | public void setOnSeekCompleteListener(MediaPlayer.OnSeekCompleteListener l) { 150 | mOnSeekCompleteListener = l; 151 | } 152 | 153 | /** 方便网络链接加载回调 */ 154 | public void setOnBufferingUpdateListener( 155 | MediaPlayer.OnBufferingUpdateListener l 156 | ){ 157 | mOnBufferingUpdateListener = l; 158 | } 159 | 160 | public static interface OnPlayStateListener { 161 | public void onStateChanged(boolean isPlaying); 162 | } 163 | 164 | public void setOnCompletionListener(MediaPlayer.OnCompletionListener l) { 165 | mOnCompletionListener = l; 166 | } 167 | 168 | public void setVideoPath(String path) { 169 | // && MediaUtils.isNative(path) 170 | if (!TextUtils.isEmpty(path)) { 171 | mTargetState = STATE_PREPARED; 172 | openVideo(Uri.parse(path)); 173 | } 174 | } 175 | 176 | public int getVideoWidth() { 177 | return mVideoWidth; 178 | } 179 | 180 | public int getVideoHeight() { 181 | return mVideoHeight; 182 | } 183 | 184 | public void reOpen() { 185 | mTargetState = STATE_PREPARED; 186 | openVideo(mUri); 187 | } 188 | 189 | public int getDuration() { 190 | return mDuration; 191 | } 192 | 193 | /** 重试 */ 194 | private void tryAgain(Exception e) { 195 | mCurrentState = STATE_ERROR; 196 | openVideo(mUri); 197 | } 198 | 199 | public void start() { 200 | mTargetState = STATE_PLAYING; 201 | //可用状态{Prepared, Started, Paused, PlaybackCompleted} 202 | if (mMediaPlayer != null && (mCurrentState == STATE_PREPARED || mCurrentState == STATE_PAUSED || mCurrentState == STATE_PLAYING || mCurrentState == STATE_PLAYBACK_COMPLETED)) { 203 | try { 204 | if (!isPlaying()) 205 | mMediaPlayer.start(); 206 | mCurrentState = STATE_PLAYING; 207 | if (mOnPlayStateListener != null) 208 | mOnPlayStateListener.onStateChanged(true); 209 | } catch (IllegalStateException e) { 210 | tryAgain(e); 211 | } catch (Exception e) { 212 | tryAgain(e); 213 | } 214 | } 215 | } 216 | 217 | public void pause() { 218 | mTargetState = STATE_PAUSED; 219 | //可用状态{Started, Paused} 220 | if (mMediaPlayer != null && (mCurrentState == STATE_PLAYING)) { 221 | try { 222 | mMediaPlayer.pause(); 223 | mCurrentState = STATE_PAUSED; 224 | if (mOnPlayStateListener != null) 225 | mOnPlayStateListener.onStateChanged(false); 226 | } catch (IllegalStateException e) { 227 | tryAgain(e); 228 | } catch (Exception e) { 229 | tryAgain(e); 230 | } 231 | } 232 | } 233 | 234 | /** 处理音量键 */ 235 | public void dispatchKeyEvent(Context context, KeyEvent event) { 236 | switch (event.getKeyCode()) { 237 | case KeyEvent.KEYCODE_VOLUME_DOWN: 238 | case KeyEvent.KEYCODE_VOLUME_UP: 239 | setVolume(getSystemVolumn(context)); 240 | break; 241 | } 242 | } 243 | 244 | public void setVolume(float volume) { 245 | //可用状态{Idle, Initialized, Stopped, Prepared, Started, Paused, PlaybackCompleted} 246 | if (mMediaPlayer != null && (mCurrentState == STATE_PREPARED || mCurrentState == STATE_PLAYING || mCurrentState == STATE_PAUSED || mCurrentState == STATE_PLAYBACK_COMPLETED)) { 247 | try { 248 | mMediaPlayer.setVolume(volume, volume); 249 | } catch (Exception e) { 250 | 251 | } 252 | } 253 | } 254 | public void setLooping(boolean looping) { 255 | //可用状态{Idle, Initialized, Stopped, Prepared, Started, Paused, PlaybackCompleted} 256 | if (mMediaPlayer != null && (mCurrentState == STATE_PREPARED || mCurrentState == STATE_PLAYING || mCurrentState == STATE_PAUSED || mCurrentState == STATE_PLAYBACK_COMPLETED)) { 257 | try { 258 | mMediaPlayer.setLooping(looping); 259 | } catch (Exception e) { 260 | } 261 | } 262 | } 263 | 264 | public void seekTo(int msec) { 265 | //可用状态{Prepared, Started, Paused, PlaybackCompleted} 266 | if (mMediaPlayer != null && (mCurrentState == STATE_PREPARED || mCurrentState == STATE_PLAYING || mCurrentState == STATE_PAUSED || mCurrentState == STATE_PLAYBACK_COMPLETED)) { 267 | try { 268 | if (msec < 0) 269 | msec = 0; 270 | mMediaPlayer.seekTo(msec); 271 | } catch (IllegalStateException e) { 272 | } catch (Exception e) { 273 | } 274 | } 275 | } 276 | 277 | /** 获取当前播放位置 */ 278 | public int getCurrentPosition() { 279 | int position = 0; 280 | //可用状态{Idle, Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted} 281 | if (mMediaPlayer != null) { 282 | switch (mCurrentState) { 283 | case STATE_PLAYBACK_COMPLETED: 284 | position = getDuration(); 285 | break; 286 | case STATE_PLAYING: 287 | case STATE_PAUSED: 288 | try { 289 | position = mMediaPlayer.getCurrentPosition(); 290 | } catch (IllegalStateException e) { 291 | } catch (Exception e) { 292 | } 293 | break; 294 | } 295 | } 296 | return position; 297 | } 298 | 299 | public boolean isPlaying() { 300 | //可用状态{Idle, Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted} 301 | if (mMediaPlayer != null && mCurrentState == STATE_PLAYING) { 302 | try { 303 | return mMediaPlayer.isPlaying(); 304 | } catch (IllegalStateException e) { 305 | } catch (Exception e) { 306 | } 307 | } 308 | return false; 309 | } 310 | 311 | /** 调用release方法以后MediaPlayer无法再恢复使用 */ 312 | public void release() { 313 | mTargetState = STATE_RELEASED; 314 | mCurrentState = STATE_RELEASED; 315 | try{ 316 | mSurfaceHolder.removeCallback(this); 317 | mSurfaceHolder = null; 318 | }catch (Exception ignore){} 319 | if (mMediaPlayer != null) { 320 | try { 321 | mMediaPlayer.release(); 322 | } catch (IllegalStateException e) { 323 | } catch (Exception e) { 324 | } 325 | mMediaPlayer = null; 326 | } 327 | } 328 | 329 | public SurfaceHolder getSurfaceHolder() { 330 | return mSurfaceHolder; 331 | } 332 | 333 | /** 支持网络链接 */ 334 | public void openVideo(Uri uri) { 335 | if (uri == null || mSurfaceHolder == null || getContext() == null) { 336 | // not ready for playback just yet, will try again later 337 | if (mSurfaceHolder == null && uri != null) { 338 | mUri = uri; 339 | } 340 | return; 341 | } 342 | 343 | mUri = uri; 344 | mDuration = 0; 345 | 346 | //Idle 状态:当使用new()方法创建一个MediaPlayer对象或者调用了其reset()方法时,该MediaPlayer对象处于idle状态。 347 | //End 状态:通过release()方法可以进入End状态,只要MediaPlayer对象不再被使用,就应当尽快将其通过release()方法释放掉 348 | //Initialized 状态:这个状态比较简单,MediaPlayer调用setDataSource()方法就进入Initialized状态,表示此时要播放的文件已经设置好了。 349 | //Prepared 状态:初始化完成之后还需要通过调用prepare()或prepareAsync()方法,这两个方法一个是同步的一个是异步的,只有进入Prepared状态,才表明MediaPlayer到目前为止都没有错误,可以进行文件播放。 350 | 351 | Exception exception = null; 352 | try { 353 | if (mMediaPlayer == null) { 354 | mMediaPlayer = new MediaPlayer(); 355 | mMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener); 356 | mMediaPlayer.setOnPreparedListener(mPreparedListener); 357 | mMediaPlayer.setOnCompletionListener(mCompletionListener); 358 | mMediaPlayer.setOnErrorListener(mErrorListener); 359 | mMediaPlayer.setOnVideoSizeChangedListener(mVideoSizeChangedListener); 360 | mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); 361 | mMediaPlayer.setOnSeekCompleteListener(mSeekCompleteListener); 362 | mMediaPlayer.setOnInfoListener(mInfoListener); 363 | // mMediaPlayer.setScreenOnWhilePlaying(true); 364 | // mMediaPlayer.setVolume(mSystemVolumn, mSystemVolumn); 365 | mMediaPlayer.setDisplay(mSurfaceHolder); 366 | } else { 367 | mMediaPlayer.reset(); 368 | } 369 | mMediaPlayer.setDataSource(getContext(), uri); 370 | 371 | // if (mLooping) 372 | // mMediaPlayer.setLooping(true);//循环播放 373 | mMediaPlayer.prepareAsync(); 374 | // we don't set the target state here either, but preserve the 375 | // target state that was there before. 376 | mCurrentState = STATE_PREPARING; 377 | } catch (IOException ex) { 378 | exception = ex; 379 | } catch (IllegalArgumentException ex) { 380 | exception = ex; 381 | } catch (Exception ex) { 382 | exception = ex; 383 | } 384 | if (exception != null) { 385 | mCurrentState = STATE_ERROR; 386 | if (mErrorListener != null) 387 | mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0); 388 | } 389 | } 390 | 391 | private MediaPlayer.OnCompletionListener mCompletionListener = new MediaPlayer.OnCompletionListener() { 392 | @Override 393 | public void onCompletion(MediaPlayer mp) { 394 | mCurrentState = STATE_PLAYBACK_COMPLETED; 395 | // mTargetState = STATE_PLAYBACK_COMPLETED; 396 | if (mOnCompletionListener != null) 397 | mOnCompletionListener.onCompletion(mp); 398 | } 399 | }; 400 | 401 | MediaPlayer.OnPreparedListener mPreparedListener = new MediaPlayer.OnPreparedListener() { 402 | @Override 403 | public void onPrepared(MediaPlayer mp) { 404 | //必须是正常状态 405 | if (mCurrentState == STATE_PREPARING) { 406 | mCurrentState = STATE_PREPARED; 407 | try { 408 | mDuration = mp.getDuration(); 409 | } catch (IllegalStateException e) { 410 | } 411 | 412 | try { 413 | mVideoWidth = mp.getVideoWidth(); 414 | mVideoHeight = mp.getVideoHeight(); 415 | } catch (IllegalStateException e) { 416 | } 417 | 418 | switch (mTargetState) { 419 | case STATE_PREPARED: 420 | if (mOnPreparedListener != null) 421 | mOnPreparedListener.onPrepared(mMediaPlayer); 422 | break; 423 | case STATE_PLAYING: 424 | start(); 425 | break; 426 | } 427 | } 428 | } 429 | }; 430 | 431 | OnVideoSizeChangedListener mVideoSizeChangedListener = new OnVideoSizeChangedListener() { 432 | 433 | @Override 434 | public void onVideoSizeChanged(MediaPlayer mp, int width, int height) { 435 | mVideoWidth = width; 436 | mVideoHeight = height; 437 | if (mOnVideoSizeChangedListener != null) 438 | mOnVideoSizeChangedListener.onVideoSizeChanged(mp, width, height); 439 | } 440 | 441 | }; 442 | 443 | OnInfoListener mInfoListener = new OnInfoListener() { 444 | 445 | @Override 446 | public boolean onInfo(MediaPlayer mp, int what, int extra) { 447 | if (mOnInfoListener != null) 448 | mOnInfoListener.onInfo(mp, what, extra); 449 | return false; 450 | } 451 | }; 452 | 453 | private MediaPlayer.OnSeekCompleteListener mSeekCompleteListener = new MediaPlayer.OnSeekCompleteListener() { 454 | 455 | @Override 456 | public void onSeekComplete(MediaPlayer mp) { 457 | if (mOnSeekCompleteListener != null) 458 | mOnSeekCompleteListener.onSeekComplete(mp); 459 | } 460 | }; 461 | 462 | private MediaPlayer.OnErrorListener mErrorListener = new MediaPlayer.OnErrorListener() { 463 | @Override 464 | public boolean onError(MediaPlayer mp, int framework_err, int impl_err) { 465 | mCurrentState = STATE_ERROR; 466 | // mTargetState = STATE_ERROR; 467 | //FIX,可以考虑出错以后重新开始 468 | if (mOnErrorListener != null) 469 | mOnErrorListener.onError(mp, framework_err, impl_err); 470 | 471 | return true; 472 | } 473 | }; 474 | 475 | /** 是否可用 */ 476 | public boolean isPrepared() { 477 | return mMediaPlayer != null && (mCurrentState == STATE_PREPARED); 478 | } 479 | 480 | public boolean isComplate(){ 481 | return mMediaPlayer != null && (mCurrentState == STATE_PLAYBACK_COMPLETED); 482 | } 483 | 484 | /** 是否已经释放 */ 485 | public boolean isRelease() { 486 | return mMediaPlayer == null || mCurrentState == STATE_IDLE || mCurrentState == STATE_ERROR || mCurrentState == STATE_RELEASED; 487 | } 488 | 489 | private Handler mVideoHandler = new Handler() { 490 | @Override 491 | public void handleMessage(Message msg) { 492 | switch (msg.what) { 493 | case HANDLER_MESSAGE_PARSE: 494 | pause(); 495 | break; 496 | case HANDLER_MESSAGE_LOOP: 497 | if (isPlaying()) { 498 | seekTo(msg.arg1); 499 | sendMessageDelayed(mVideoHandler.obtainMessage(HANDLER_MESSAGE_LOOP, msg.arg1, msg.arg2), msg.arg2); 500 | } 501 | break; 502 | default: 503 | break; 504 | } 505 | super.handleMessage(msg); 506 | } 507 | }; 508 | 509 | /** 定时暂停 */ 510 | public void pauseDelayed(int delayMillis) { 511 | if (mVideoHandler.hasMessages(HANDLER_MESSAGE_PARSE)) 512 | mVideoHandler.removeMessages(HANDLER_MESSAGE_PARSE); 513 | mVideoHandler.sendEmptyMessageDelayed(HANDLER_MESSAGE_PARSE, delayMillis); 514 | } 515 | 516 | /** 暂停并且清除定时任务 */ 517 | public void pauseClearDelayed() { 518 | pause(); 519 | if (mVideoHandler.hasMessages(HANDLER_MESSAGE_PARSE)) 520 | mVideoHandler.removeMessages(HANDLER_MESSAGE_PARSE); 521 | if (mVideoHandler.hasMessages(HANDLER_MESSAGE_LOOP)) 522 | mVideoHandler.removeMessages(HANDLER_MESSAGE_LOOP); 523 | } 524 | 525 | /** 区域内循环播放 */ 526 | public void loopDelayed(int startTime, int endTime) { 527 | if (mVideoHandler.hasMessages(HANDLER_MESSAGE_PARSE)) 528 | mVideoHandler.removeMessages(HANDLER_MESSAGE_PARSE); 529 | if (mVideoHandler.hasMessages(HANDLER_MESSAGE_LOOP)) 530 | mVideoHandler.removeMessages(HANDLER_MESSAGE_LOOP); 531 | int delayMillis = endTime - startTime; 532 | seekTo(startTime); 533 | if (!isPlaying()) 534 | start(); 535 | if (mVideoHandler.hasMessages(HANDLER_MESSAGE_LOOP)) 536 | mVideoHandler.removeMessages(HANDLER_MESSAGE_LOOP); 537 | mVideoHandler.sendMessageDelayed(mVideoHandler.obtainMessage(HANDLER_MESSAGE_LOOP, getCurrentPosition(), delayMillis), delayMillis); 538 | } 539 | 540 | @Override 541 | public void surfaceCreated(SurfaceHolder holder) { 542 | boolean needReOpen = (mSurfaceHolder == null); 543 | mSurfaceHolder = holder; 544 | if (needReOpen) { 545 | reOpen(); 546 | } 547 | } 548 | 549 | @Override 550 | public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { 551 | mSurfaceHolder = holder; 552 | } 553 | 554 | @Override 555 | public void surfaceDestroyed(SurfaceHolder holder) { 556 | mSurfaceHolder = null; 557 | release(); 558 | } 559 | 560 | @Override 561 | protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 562 | super.onMeasure(widthMeasureSpec, heightMeasureSpec); 563 | } 564 | } 565 | -------------------------------------------------------------------------------- /wechatsmallvideoview/src/main/java/com/example/wechatsmallvideoview/SurfaceVideoViewCreator.java: -------------------------------------------------------------------------------- 1 | package com.example.wechatsmallvideoview; 2 | 3 | import android.annotation.TargetApi; 4 | import android.app.Activity; 5 | import android.media.MediaPlayer; 6 | import android.os.AsyncTask; 7 | import android.os.Build; 8 | import android.os.Environment; 9 | import android.util.Log; 10 | import android.util.TypedValue; 11 | import android.view.KeyEvent; 12 | import android.view.LayoutInflater; 13 | import android.view.View; 14 | import android.view.ViewGroup; 15 | import android.widget.Button; 16 | import android.widget.ImageView; 17 | 18 | import java.io.File; 19 | import java.io.FileOutputStream; 20 | import java.io.IOException; 21 | import java.io.InputStream; 22 | import java.net.HttpURLConnection; 23 | import java.net.MalformedURLException; 24 | import java.net.URL; 25 | 26 | /** 27 | * 作者:林冠宏 28 | *
29 | * My GitHub : https://github.com/af913337456/ 30 | *
31 | * My Blog : http://www.cnblogs.com/linguanh/ 32 | *
33 | * on 2017/4/26.
34 | */
35 |
36 |
37 | public abstract class SurfaceVideoViewCreator
38 | implements
39 | SurfaceVideoView.OnPlayStateListener, MediaPlayer.OnErrorListener,
40 | MediaPlayer.OnPreparedListener, View.OnClickListener, MediaPlayer.OnCompletionListener,
41 | MediaPlayer.OnInfoListener
42 | {
43 |
44 | private final static String TAG="zzzzz";
45 |
46 | private SurfaceVideoView surfaceVideoView;
47 | private LoadingCircleView progressBar;
48 | private Button statusButton;
49 | private ImageView surface_video_screenshot;
50 |
51 | private File videoFile = null;
52 | private boolean isUseCache = false;
53 | private boolean mNeedResume;
54 |
55 | private boolean isFinishDownload = false;
56 | public boolean debugModel = false;
57 |
58 | private String videoPath;
59 |
60 | protected abstract Activity getActivity();
61 | protected abstract boolean setAutoPlay();
62 | protected abstract int getSurfaceWidth();
63 | protected abstract int getSurfaceHeight();
64 | protected abstract void setThumbImage(ImageView thumbImageView);
65 | protected abstract String getSecondVideoCachePath();
66 | protected abstract String getVideoPath();
67 |
68 | public void setUseCache(boolean useCache){
69 | this.isUseCache = useCache;
70 | }
71 |
72 | public SurfaceVideoViewCreator(Activity activity, ViewGroup container)
73 | {
74 | View view = LayoutInflater
75 | .from(activity)
76 | .inflate(R.layout.surface_video_view_layout,container,false);
77 |
78 | container.addView(view);
79 |
80 | surfaceVideoView = (SurfaceVideoView) view.findViewById(R.id.surface_video_view);
81 | progressBar = (LoadingCircleView) view.findViewById(R.id.surface_video_progress);
82 | statusButton = (Button) view.findViewById(R.id.surface_video_button);
83 | surface_video_screenshot = (ImageView) view.findViewById(R.id.surface_video_screenshot);
84 | setThumbImage(surface_video_screenshot);
85 |
86 |
87 | int width = getSurfaceWidth();
88 | if(width != 0){
89 | /** 默认就是手机宽度 */
90 | surfaceVideoView.getLayoutParams().width = width;
91 | }
92 | view.findViewById(R.id.surface_video_container).getLayoutParams().height
93 | =
94 | (int) TypedValue.applyDimension
95 | (
96 | TypedValue.COMPLEX_UNIT_DIP, getSurfaceHeight(), container.getContext().getResources().getDisplayMetrics()
97 | );
98 | view.findViewById(R.id.surface_video_container).requestLayout();
99 |
100 | surfaceVideoView.setOnPreparedListener(this);
101 | surfaceVideoView.setOnPlayStateListener(this);
102 | surfaceVideoView.setOnErrorListener(this);
103 | surfaceVideoView.setOnInfoListener(this);
104 | surfaceVideoView.setOnCompletionListener(this);
105 |
106 | surfaceVideoView.setOnClickListener(this);
107 |
108 | videoPath = getVideoPath();
109 | if(setAutoPlay()) {
110 | prepareStart(videoPath);
111 | }else {
112 | statusButton.setOnClickListener(new View.OnClickListener() {
113 | @Override
114 | public void onClick(View v) {
115 | /** 点击即加载 */
116 | /** 这里进行本地是否存在判断 */
117 | prepareStart(videoPath);
118 | }
119 | });
120 | }
121 | }
122 |
123 | private void prepareStart(String videoPath){
124 | try{
125 | String rootPath = Environment.getExternalStorageDirectory().getAbsolutePath()
126 | + File.separator+"myvideos/";
127 | File file = new File(rootPath);
128 | if(!file.exists()){
129 | if(!file.mkdirs()){
130 | throw new NullPointerException("创建 rootPath 失败,注意 6.0+ 的动态申请权限");
131 | }
132 | }
133 |
134 | String[] temp = videoPath.split("/");
135 | videoFile =
136 | new File(Environment.getExternalStorageDirectory().getAbsolutePath()
137 | + File.separator+"myvideos/"+temp[temp.length-1]);
138 |
139 | videoPath = getVideoPath();
140 | if(debugModel){
141 | /** 测试模式 */
142 | if(isUseCache){
143 | Log.e(TAG,"使用缓存播放");
144 | play(videoFile.getAbsolutePath());
145 | }else{
146 | if(videoFile.exists()){
147 | videoFile.delete();
148 | videoFile.createNewFile();
149 | }
150 | new MyAsyncTask().execute(videoPath);
151 | }
152 | return;
153 | }
154 | /** 实际情况 */
155 | if(videoFile.exists()){ /** 存在缓存 */
156 | play(videoFile.getAbsolutePath());
157 | }else{
158 | String secondCacheFilePath = getSecondVideoCachePath(); /** 第二缓存目录,应对此种情况,例如,本地上传是一个目录,那么就可能要到这个目录找一下 */
159 | if(secondCacheFilePath != null){
160 | play(secondCacheFilePath);
161 | return;
162 | }
163 | videoFile.createNewFile();
164 | new MyAsyncTask().execute(videoPath); /** 下载再播放 */
165 | }
166 |
167 | }catch (Exception e){
168 | Log.d(TAG,e.toString());
169 | }
170 | }
171 |
172 | public void onKeyEvent(KeyEvent event){
173 | switch (event.getKeyCode()) {// 跟随系统音量走
174 | case KeyEvent.KEYCODE_VOLUME_DOWN:
175 | case KeyEvent.KEYCODE_VOLUME_UP:
176 | if (!getActivity().isFinishing())
177 | surfaceVideoView.dispatchKeyEvent(getActivity(), event);
178 | break;
179 | }
180 | }
181 |
182 | private boolean isWebUrl(String videoPath){
183 | return videoPath.contains("https://")
184 | || videoPath.contains("http://")
185 | || videoPath.contains("ftp://");
186 | }
187 |
188 | public void onDestroy(){
189 | progressBar = null;
190 | statusButton = null;
191 | interceptFlag = true;
192 | if(!isFinishDownload && isWebUrl(videoPath)){
193 | // 如果还没下载完,清空缓存文件
194 | // 同时判断是否是网址链接,防止本地的被删除
195 | if(videoFile != null){
196 | Log.d(TAG, "还没下载完,清空缓存文件");
197 | videoFile.delete();
198 | }
199 | }
200 | isFinishDownload = false;
201 | if (surfaceVideoView != null) {
202 | surfaceVideoView.release();
203 | surfaceVideoView = null;
204 | }
205 | }
206 |
207 | public void onResume(){
208 | if (surfaceVideoView != null && mNeedResume) {
209 | mNeedResume = false;
210 | interceptFlag = false;
211 | if (surfaceVideoView.isRelease())
212 | surfaceVideoView.reOpen();
213 | else
214 | surfaceVideoView.start();
215 | }
216 | }
217 |
218 | public void onPause(){
219 | if (surfaceVideoView != null) {
220 | if (surfaceVideoView.isPlaying()) {
221 | mNeedResume = true;
222 | surfaceVideoView.pause();
223 | }
224 | }
225 | }
226 |
227 | private void play(String path){
228 | if(!surfaceVideoView.isPlaying()){
229 | progressBar.setVisibility(View.GONE);
230 | statusButton.setVisibility(View.GONE);
231 | surfaceVideoView.setVideoPath(path);
232 | }
233 | }
234 |
235 | @Override
236 | public void onCompletion(MediaPlayer mp) {
237 | if (!getActivity().isFinishing())
238 | surfaceVideoView.reOpen();
239 | }
240 |
241 | @Override
242 | public boolean onError(MediaPlayer mp, int what, int extra) {
243 | Log.d(TAG,"播放失败 onError "+what);
244 | return false;
245 | }
246 |
247 | @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
248 | @Override
249 | public boolean onInfo(MediaPlayer mp, int what, int extra) {
250 | switch (what) {
251 | case MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING:
252 | /** 音频和视频数据不正确 */
253 | Log.d(TAG,"音频和视频数据不正确 ");
254 | break;
255 | case MediaPlayer.MEDIA_INFO_BUFFERING_START: /** 缓冲开始 */
256 | if (!getActivity().isFinishing()) {
257 | surfaceVideoView.pause();
258 | }
259 | break;
260 | case MediaPlayer.MEDIA_INFO_BUFFERING_END: /** 缓冲结束 */
261 | if (!getActivity().isFinishing())
262 | surfaceVideoView.start();
263 | break;
264 | case MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START: /** 渲染开始 rendering */
265 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
266 | surfaceVideoView.setBackground(null);
267 | } else {
268 | surfaceVideoView.setBackgroundDrawable(null);
269 | }
270 | break;
271 | }
272 | return false;
273 | }
274 |
275 | @Override
276 | public void onPrepared(MediaPlayer mp) {
277 | Log.d(TAG,"播放开始 onPrepared ");
278 | surfaceVideoView.setVolume(SurfaceVideoView.getSystemVolumn(getActivity()));
279 | surfaceVideoView.start();
280 | //progressBar.setVisibility(View.GONE);
281 | surface_video_screenshot.setVisibility(View.GONE);
282 | }
283 |
284 | @Override
285 | public void onClick(View v) {
286 | getActivity().finish();
287 | }
288 |
289 | @Override
290 | public void onStateChanged(boolean isPlaying) {
291 | statusButton.setVisibility(isPlaying ? View.GONE : View.VISIBLE);
292 | }
293 |
294 |
295 | /** 内部下载类,微信的机制是下载好再播放的,也可以直接边下载边播放 */
296 | private boolean interceptFlag = false;
297 | private class MyAsyncTask extends AsyncTask