├── .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 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /.idea/copyright/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 19 | 20 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 19 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 46 | 47 | 48 | 49 | 50 | 51 | 56 | 57 | 58 | 59 | 60 | 61 | 1.8 62 | 63 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 79 | 80 | 81 | 82 | 83 | 84 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | > 作者:林冠宏 / 指尖下的幽灵 2 | 3 | > 掘金:https://juejin.im/user/587f0dfe128fe100570ce2d8 4 | 5 | > 博客:http://www.cnblogs.com/linguanh/ 6 | 7 | > GitHub : https://github.com/af913337456/ 8 | 9 | > 为了您的直观体验,请务必看完下面 gif 图,源码 gitHub 链接在其之后。 10 | 11 | 为了避免大家浪费时间,直接先看下面的 Gif,略大,请耐心点。看完后,若你觉得会需要到,那么就请听我继续。 12 | 13 | gif 演示太大,github 显示不了。看视频链接可以去文章:https://juejin.im/post/59006c76a0bb9f0065dbc835 中看 14 | 15 | ### 引用库(use library) 16 | 17 | ```java 18 | repositories { 19 | jcenter() 20 | maven { url "https://jitpack.io" } 21 | } 22 | compile 'com.github.af913337456:WeChatVideoView:1.0' 23 | ``` 24 | 25 | ### 功能点 26 | 27 | 如果你看完上面的gif图,你会发现如下几点功能 (Function list): 28 | 29 | 1,直观的 30 | * 播放前,可以显示封面缩略图 31 | * 播放时,如果还没有本地缓存,那么先进行下载 32 | * 下载过程中,显示圆型区域进度效果 33 | * 下载后,播放完毕后可以循环播放 34 | * 播放已经播放过的,是具备本地缓存的,也就是既能播放网络,也能播放本地 35 | 36 | 2,隐藏的 37 | * 低耗电量 38 | * 低内存占用 39 | * 无延迟图与视频切换 40 | * 低耦合,高内聚,几行代码接入 41 | 42 | ### 解析 43 | 直观的功能点,几乎就是和新版```微信```的一样,从朋友圈点击一个视频,然后进入到一个 Activity 页面进行加载以及播放。 44 | 45 | ##### 为什么低耗电量和低内存占用? 46 | 因为采用的是 SurfaceView 而不是 TextureView,图与视频切换的切换延迟也是这个原因。 47 | 48 | ##### 在你的 Activity 中这样使用 49 | ![](https://dn-mhke0kuv.qbox.me/3c1516f88ed7d3d89a74) 50 | 这样就会以 id 为 activity_main 的 Relativelayout 为父容器装载。 51 | 因为要避免内存泄露,所以你还需要做完下面的一些步骤,不会超过6行代码。 52 | ![](https://dn-mhke0kuv.qbox.me/b1f9ce326062f328b711) 53 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 25 5 | buildToolsVersion "25.0.2" 6 | defaultConfig { 7 | applicationId "com.example.asus.wechatvideoview" 8 | minSdkVersion 15 9 | targetSdkVersion 25 10 | versionCode 1 11 | versionName "1.0" 12 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | } 21 | 22 | dependencies { 23 | compile fileTree(dir: 'libs', include: ['*.jar']) 24 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { 25 | exclude group: 'com.android.support', module: 'support-annotations' 26 | }) 27 | compile project(':wechatsmallvideoview') 28 | compile 'com.android.support:appcompat-v7:25.2.0' 29 | compile 'com.github.bumptech.glide:glide:3.7.0' 30 | testCompile 'junit:junit:4.12' 31 | } 32 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in D:\Sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/example/asus/wechatvideoview/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.example.asus.wechatvideoview; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Instrumentation test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() throws Exception { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("com.example.asus.wechatvideoview", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 12 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /app/src/main/java/com/example/asus/wechatvideoview/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.example.asus.wechatvideoview; 2 | 3 | import android.app.Activity; 4 | import android.content.pm.PackageManager; 5 | import android.os.Bundle; 6 | import android.support.v4.app.ActivityCompat; 7 | import android.support.v7.app.AppCompatActivity; 8 | import android.view.KeyEvent; 9 | import android.widget.ImageView; 10 | import android.widget.RelativeLayout; 11 | 12 | import com.bumptech.glide.Glide; 13 | import com.bumptech.glide.load.engine.DiskCacheStrategy; 14 | import com.example.wechatsmallvideoview.SurfaceVideoViewCreator; 15 | 16 | public class MainActivity extends AppCompatActivity { 17 | 18 | private SurfaceVideoViewCreator surfaceVideoViewCreator; 19 | 20 | @Override 21 | protected void onCreate(Bundle savedInstanceState) { 22 | super.onCreate(savedInstanceState); 23 | setContentView(R.layout.activity_main); 24 | 25 | ActivityCompat.requestPermissions( 26 | MainActivity.this, 27 | new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 28 | 1 29 | ); 30 | 31 | surfaceVideoViewCreator = 32 | new SurfaceVideoViewCreator(this,(RelativeLayout)findViewById(R.id.activity_main)) { 33 | @Override 34 | protected Activity getActivity() { 35 | return MainActivity.this; /** 当前的 Activity */ 36 | } 37 | 38 | @Override 39 | protected boolean setAutoPlay() { 40 | return false; /** true 适合用于,已进入就自动播放的情况 */ 41 | } 42 | 43 | @Override 44 | protected int getSurfaceWidth() { 45 | return 0; /** Video 的显示区域宽度,0 就是适配手机宽度 */ 46 | } 47 | @Override 48 | protected int getSurfaceHeight() { 49 | return 250; /** Video 的显示区域高度,dp 为单位 */ 50 | } 51 | @Override 52 | protected void setThumbImage(ImageView thumbImageView) { 53 | Glide.with(MainActivity.this) 54 | .load("http://img5.imgtn.bdimg.com/it/u=2306924532,2222049363&fm=27&gp=0.jpg") 55 | .centerCrop() 56 | .diskCacheStrategy(DiskCacheStrategy.ALL) 57 | .placeholder(R.drawable.all_darkbackground) 58 | .dontAnimate() 59 | .into(thumbImageView); 60 | } 61 | 62 | /** 这个是设置返回自己的缓存路径, 63 | * 应对这种情况: 64 | * 录制的时候是在另外的目录,播放的时候默认是在下载的目录,所以可以在这个方法处理返回缓存 65 | * */ 66 | @Override 67 | protected String getSecondVideoCachePath() { 68 | return null; 69 | } 70 | 71 | @Override 72 | protected String getVideoPath() { 73 | return "http://www.w3school.com.cn/example/html5/mov_bbb.mp4"; 74 | } 75 | }; 76 | surfaceVideoViewCreator.debugModel = true; 77 | surfaceVideoViewCreator.setUseCache(getIntent().getBooleanExtra("useCache",false)); 78 | } 79 | 80 | @Override 81 | protected void onPause() { 82 | super.onPause(); 83 | surfaceVideoViewCreator.onPause(); 84 | } 85 | 86 | @Override 87 | protected void onResume() { 88 | super.onResume(); 89 | surfaceVideoViewCreator.onResume(); 90 | } 91 | 92 | @Override 93 | protected void onDestroy() { 94 | super.onDestroy(); 95 | surfaceVideoViewCreator.onDestroy(); 96 | } 97 | 98 | @Override 99 | public boolean dispatchKeyEvent(KeyEvent event) { 100 | surfaceVideoViewCreator.onKeyEvent(event); /** 声音的大小调节 */ 101 | return super.dispatchKeyEvent(event); 102 | } 103 | 104 | @Override 105 | public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { 106 | switch (requestCode) { 107 | case 1: 108 | if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { 109 | 110 | break; 111 | } 112 | } 113 | super.onRequestPermissionsResult(requestCode, permissions, grantResults); 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /app/src/main/java/com/example/asus/wechatvideoview/WelcomeActivity.java: -------------------------------------------------------------------------------- 1 | package com.example.asus.wechatvideoview; 2 | 3 | import android.app.Activity; 4 | import android.content.Intent; 5 | import android.os.Bundle; 6 | import android.view.View; 7 | import android.widget.Button; 8 | import android.widget.LinearLayout; 9 | 10 | /** 11 | * 作者:林冠宏 12 | *

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 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/af913337456/WeChatVideoView/2ab5b3ddbeba0fb385af7d12b7934dd3f87c97d7/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/af913337456/WeChatVideoView/2ab5b3ddbeba0fb385af7d12b7934dd3f87c97d7/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/af913337456/WeChatVideoView/2ab5b3ddbeba0fb385af7d12b7934dd3f87c97d7/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/af913337456/WeChatVideoView/2ab5b3ddbeba0fb385af7d12b7934dd3f87c97d7/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/af913337456/WeChatVideoView/2ab5b3ddbeba0fb385af7d12b7934dd3f87c97d7/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/values-w820dp/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 64dp 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3F51B5 4 | #303F9F 5 | #FF4081 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16dp 4 | 16dp 5 | 6 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | WeChatVideoView 3 | 4 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/test/java/com/example/asus/wechatvideoview/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.example.asus.wechatvideoview; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | @Test 14 | public void addition_isCorrect() throws Exception { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | repositories { 5 | jcenter() 6 | } 7 | dependencies { 8 | classpath 'com.android.tools.build:gradle:2.2.3' 9 | 10 | // NOTE: Do not place your application dependencies here; they belong 11 | // in the individual module build.gradle files 12 | } 13 | } 14 | 15 | allprojects { 16 | repositories { 17 | jcenter() 18 | } 19 | } 20 | 21 | task clean(type: Delete) { 22 | delete rootProject.buildDir 23 | } 24 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | org.gradle.jvmargs=-Xmx1536m 13 | 14 | # When configured, Gradle will run in incubating parallel mode. 15 | # This option should only be used with decoupled projects. More details, visit 16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 17 | # org.gradle.parallel=true 18 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/af913337456/WeChatVideoView/2ab5b3ddbeba0fb385af7d12b7934dd3f87c97d7/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Dec 28 10:00:20 PST 2015 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app', ':wechatsmallvideoview' 2 | -------------------------------------------------------------------------------- /wechatsmallvideoview/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /wechatsmallvideoview/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | 3 | android { 4 | compileSdkVersion 25 5 | buildToolsVersion "25.0.2" 6 | 7 | defaultConfig { 8 | minSdkVersion 15 9 | targetSdkVersion 25 10 | versionCode 1 11 | versionName "1.0" 12 | 13 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 14 | 15 | } 16 | buildTypes { 17 | release { 18 | minifyEnabled false 19 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 20 | } 21 | } 22 | } 23 | 24 | dependencies { 25 | compile fileTree(dir: 'libs', include: ['*.jar']) 26 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { 27 | exclude group: 'com.android.support', module: 'support-annotations' 28 | }) 29 | compile 'com.android.support:appcompat-v7:25.2.0' 30 | testCompile 'junit:junit:4.12' 31 | } 32 | -------------------------------------------------------------------------------- /wechatsmallvideoview/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in D:\Sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /wechatsmallvideoview/src/androidTest/java/com/example/wechatsmallvideoview/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.example.wechatsmallvideoview; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Instrumentation test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() throws Exception { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("com.example.wechatsmallvideoview.test", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /wechatsmallvideoview/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /wechatsmallvideoview/src/main/java/com/example/wechatsmallvideoview/LoadingCircleView.java: -------------------------------------------------------------------------------- 1 | package com.example.wechatsmallvideoview; 2 | 3 | import android.content.Context; 4 | import android.graphics.Canvas; 5 | import android.graphics.Color; 6 | import android.graphics.Paint; 7 | import android.graphics.RectF; 8 | import android.util.AttributeSet; 9 | import android.view.View; 10 | import android.view.animation.Animation; 11 | import android.view.animation.Transformation; 12 | 13 | /** 14 | * 15 | *

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{ 298 | 299 | @Override 300 | protected void onPreExecute() { 301 | super.onPreExecute(); 302 | statusButton.setVisibility(View.GONE); 303 | progressBar.setVisibility(View.VISIBLE); 304 | } 305 | 306 | @Override 307 | protected String doInBackground(String[] params) { 308 | try { 309 | String urlPath = params[0]; 310 | URL url = new URL(urlPath); 311 | 312 | HttpURLConnection conn = (HttpURLConnection)url.openConnection(); 313 | conn.connect(); 314 | int length = conn.getContentLength(); 315 | InputStream is = conn.getInputStream(); 316 | 317 | FileOutputStream fos = new FileOutputStream(videoFile); 318 | int count = 0; 319 | byte buf[] = new byte[1024]; 320 | 321 | do{ 322 | int numread = is.read(buf); 323 | count += numread; 324 | int progress =(int)(((float)count / length) * 100); 325 | //更新进度 326 | Log.d(TAG,"更新进度 "+progress); 327 | if(numread <= 0){ 328 | publishProgress(100); 329 | break; 330 | }else{ 331 | publishProgress(progress); 332 | } 333 | fos.write(buf,0,numread); 334 | }while(!interceptFlag);//点击取消就停止下载. 335 | Log.d(TAG,"下载结束 "); 336 | isFinishDownload = true; 337 | fos.close(); 338 | is.close(); 339 | } catch (MalformedURLException e) { 340 | Log.d(TAG,e.toString()); 341 | } catch(IOException e){ 342 | // Toast.makeText(App.context,"安卓6.0+ 请动态申请文件读取权限",Toast.LENGTH_LONG).show(); 343 | Log.d(TAG,e.toString()); 344 | } 345 | return null; 346 | } 347 | 348 | @Override 349 | protected void onProgressUpdate(Integer[] values) { 350 | if(progressBar == null) 351 | return; 352 | int progress = values[0]; 353 | progressBar.setProgerss(progress,true); 354 | if(progress >= 100){ 355 | Log.d(TAG,"开始播放 "); 356 | play(videoFile.getAbsolutePath()); 357 | } 358 | } 359 | 360 | @Override 361 | protected void onPostExecute(String o) { 362 | super.onPostExecute(o); 363 | } 364 | } 365 | } 366 | -------------------------------------------------------------------------------- /wechatsmallvideoview/src/main/res/drawable/all_darkbackground.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /wechatsmallvideoview/src/main/res/drawable/ic_play_24dp.xml: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /wechatsmallvideoview/src/main/res/layout/surface_video_view_layout.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 9 | 10 | 14 | 15 | 16 | 21 | 22 |