├── .gitattributes ├── .gitignore ├── DefaultExtractorInput.png ├── LICENSE ├── README.md ├── TestPlayerActivity.png ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── assets │ └── 终于等到你.mp3 │ ├── java │ └── com │ │ └── ddc │ │ └── exoplayertest │ │ ├── AESHelper.java │ │ ├── Aes128DataSource.java │ │ ├── AitripDataSource.java │ │ ├── AitripDataSourceFactory.java │ │ ├── AppContext.java │ │ ├── TestPlayerActivity.java │ │ ├── TimeUtils.java │ │ ├── ToastUtil.java │ │ └── permission │ │ ├── OnPermissionCallback.java │ │ ├── Permission.java │ │ ├── PermissionManager.java │ │ ├── RxPermissions.java │ │ └── RxPermissionsFragment.java │ └── res │ ├── anim │ ├── dialog_in.xml │ ├── dialog_iout.xml │ ├── pophidden_anim.xml │ └── popshow_anim.xml │ ├── drawable-v24 │ └── ic_launcher_foreground.xml │ ├── drawable-xxhdpi │ └── circle_white.png │ ├── drawable │ ├── ic_launcher_background.xml │ ├── red_bt_shape.xml │ └── video_seekbar.xml │ ├── layout │ ├── activity_main.xml │ └── activity_test_player.xml │ ├── mipmap-anydpi-v26 │ ├── ic_launcher.xml │ └── ic_launcher_round.xml │ ├── mipmap-hdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-mdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-xhdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-xxhdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-xxxhdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ └── values │ ├── attrs.xml │ ├── colors.xml │ ├── dimens.xml │ ├── ids.xml │ ├── strings.xml │ ├── styles.xml │ └── theme.xml ├── build.gradle ├── dataSource.png ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto -------------------------------------------------------------------------------- /.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 | 11 | -------------------------------------------------------------------------------- /DefaultExtractorInput.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChangWeiBa/AesExoPlayer/6c1045b6557428c111fcce3c52ce59949941c9a6/DefaultExtractorInput.png -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## ExoPlayer利用自定义DataSource实现直接播放AES加密音频 2 | 3 | 开局一张图 4 | 5 | ![dataSource.png](/dataSource.png "dataSource.png") 6 | 7 | [本文博客地址](http://blog.csdn.net/wanniu/article/details/78533796 "还可以进入博客查看本文") 8 | 9 | [ExoPlayer源码浅析](http://www.jianshu.com/p/4dede867739d "ExoPlayer源码浅析") 10 | 11 | [ExoPlayer官方文档](http://www.jianshu.com/p/4dede867739d "ExoPlayer 官方文档") 12 | 13 | [ExoPlayer GitHub](https://github.com/google/ExoPlayer "ExoPlayer Github") 14 | 15 | 16 | ## 需求与适用范围 17 | 首先本文的适用范围是使用ExoPlayer框架时,直接解密播放已经经过AES加密过(或者类似需求)的音频或者视频,是利用官方demo内DefaultDataSourceFactory与DefaultDataSource改造而来。有需求就可以继续往下看了 18 | 19 | #### 0.故事的开始 20 | 故事的开始还得从新需求开始说起。公司新开了一个旅游项目,其中主要功能就是播放在线或者本地音频,这个非常非常平常的需求,让我开始EXO之旅。 21 | 22 | 为什么不使用最平常简单的MediaPlayer,因为程序员喜新厌旧哇 嘻嘻。 23 | 24 | 其中我们最主要的需求就是,下载下来的本地音频需要加密存放在本地,在播放的时候进行解密播放,以保证数据的安全性,在这里选用了常见的AES加解密。 25 | 26 | 相信这些需求应该的比较常见的类型了,在选用Exoplayer之后,在线播放什么的肯定不用花费过多时间了,但在进行本地播放的时候碰到了问题。 27 | 28 | 当初在查询ExoPlayer文档的时候是知道和看中了它的自定义资源播放功能的,官方文档和各种源码解析都说它有强大的自定义功能,但是等到我真正要实现我功能的时候,我感觉ExoPlayer是一个孤儿... 29 | 30 | 为什么在GitHub上8000+星星的ExoPlayer在百度上的资料这么少(想抄都没地方抄)。。 百度Google了一圈下来,折腾完ExtractorsFactory,折腾Mp3Extractor,完全摸错了门。后来在[stackOverflow](https://stackoverflow.com/questions/37658411/ecb-encryption-with-exoplayer "stackoverflow") 看到终于一篇关于自定义dataSource的提问,至此找到问题解决入口。 31 | 32 | 33 | ## 思路与使用方式 34 | 35 | 关于ExoPlayer的各种源码、使用解析在这就不赘叙了。正常的情况下,使用ExoPlayer默认的DefaultDataSource是完成不了直接播放AES加密音频的。 36 | 37 | 最开始,要实现播放,只能先把AES音频解密成正常的MP3音频,这样,就完全打破了最初我们要把本地下载下来的音频加密存放与播放的预想,解密过后的音频总会在文件夹中显示出来,并以正常的MP3存在,这样音频就毫无安全性可言了,也就是说没有完成需求。 38 | 39 | 为解决能直接播放AES加密音频的问题,我们采用的是自定义改写DataSourceFactory类,改写DataSource类,复用官方demo中Aes128DataSource类来完成的。 40 | 41 | 只需要改写这一系列DataSource类文件,就可以完成我们直接播放AES音频文件的需求,下面逐个进行解析。 42 | 43 | 通过前期查看和研究ExoPlayer源码我们观察到,这一系列的资源提供、分拆与解析过程在ExtractorMediaSource下的ExtractorMediaPeriod类有很清晰的体现。 44 | 45 | ![DefaultExtractorInput.png](/DefaultExtractorInput.png "DefaultExtractorInput.png") 46 | 47 | 而我们需要实现的需求中,本质上只是把MP3文件加密了一次而已,它在播放的时候,最终只需要在拆解提供资源的时候把加密的文件流解密成正常的MP3流,给ExtractorMediaSource提供正常的MP3流即可,所以并不需要再过多的进行其他复杂操作就可以完成此需求。 48 | 49 | 那么我实现的就是重写DefaultDataSourceFactory资源提供工厂类,改造DefaultDataSource,根据文件类型判断,加密的音频使用Aes128DataSource类拆解进行解密,未加密或者在线的URL继续使用getFileDataSource或者getContentDataSource原本默认的实现进行拆解。最后只需要用我们改写的factory替换默认的DataSourceFactory就可以完成我们的需求了。 50 | 51 | ![TestPlayerActivity.png](/TestPlayerActivity.png "TestPlayerActivity.png") 52 | 53 | #### 1.AitripDataSourceFactory 54 | AitripDataSourceFactory是重写的DataSourceFactory工厂类,直接copyDefaultDataSource而来。主要是重写了createDataSource()方法,用于进入资源选择类AitripDataSource 55 | 56 | ```java 57 | @Override 58 | public AitripDataSource createDataSource() { 59 | return new AitripDataSource(context, listener, baseDataSourceFactory.createDataSource()); 60 | } 61 | ``` 62 | 63 | #### 2.AitripDataSource 64 | 改写DataSource内open方法,用于扩展数据源选择方案,以让其正确选择到我们的解密Aes128DataSource类,注释基本可以解释一切。因为我在本地加密的文件是在文件名后又添加了.aitrip字段,所以只需根据文件名判断是否包含.aitrip,选择正确的DataSource解析即可。 65 | 66 | ```java 67 | @Override 68 | public long open(DataSpec dataSpec) throws IOException { 69 | Assertions.checkState(dataSource == null); 70 | // Choose the correct source for the scheme. 71 | //选择正确的数据源方案 72 | String scheme = dataSpec.uri.getScheme(); 73 | //如果URI是一个本地文件路径或本地文件的引用。 74 | Timber.e("解密:000000," + scheme + ",path:" + dataSpec.uri.getPath()); 75 | if (Util.isLocalFileUri(dataSpec.uri)) { 76 | //如果路径尾包含aitrip的文件名,使用解密类 77 | if (dataSpec.uri.getPath().endsWith(".aitrip")) { 78 | Aes128DataSource aes128DataSource = 79 | new Aes128DataSource(getFileDataSource(), Aikey.getBytes(), Aikey.getBytes()); 80 | dataSource = aes128DataSource; 81 | } else {//否则,正常解析mp3 82 | if (dataSpec.uri.getPath().startsWith("/android_asset/")) { 83 | dataSource = getAssetDataSource(); 84 | } else { 85 | dataSource = getFileDataSource(); 86 | } 87 | } 88 | } else if (SCHEME_ASSET.equals(scheme)) { 89 | dataSource = getAssetDataSource(); 90 | } else if (SCHEME_CONTENT.equals(scheme)) { 91 | dataSource = getContentDataSource(); 92 | } else if (SCHEME_RTMP.equals(scheme)) { 93 | dataSource = getRtmpDataSource(); 94 | } else { 95 | dataSource = baseDataSource; 96 | } 97 | // Open the source and return. 98 | return dataSource.open(dataSpec); 99 | } 100 | ``` 101 | #### 3.Aes128DataSource 102 | 直接copy自官方demo的AesDataSource,其本用于HLS文件播放列表解密的,但是很巧的是采用了解密方式,对我也同样适用,所以并不需要改动任何一行代码。。 103 | 它主要是实现open后,利用Aes解密方式解密文件流提供给上层使用。 104 | 105 | ```java 106 | @Override 107 | public long open(DataSpec dataSpec) throws IOException { 108 | Cipher cipher; 109 | try { 110 | cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); 111 | } catch (NoSuchAlgorithmException | NoSuchPaddingException e) { 112 | throw new RuntimeException(e); 113 | } 114 | 115 | Key cipherKey = new SecretKeySpec(encryptionKey, "AES"); 116 | AlgorithmParameterSpec cipherIV = new IvParameterSpec(encryptionIv); 117 | 118 | try { 119 | cipher.init(Cipher.DECRYPT_MODE, cipherKey, cipherIV); 120 | } catch (InvalidKeyException | InvalidAlgorithmParameterException e) { 121 | throw new RuntimeException(e); 122 | } 123 | 124 | cipherInputStream = new CipherInputStream( 125 | new DataSourceInputStream(upstream, dataSpec), cipher); 126 | 127 | return C.LENGTH_UNSET; 128 | } 129 | 130 | ``` 131 | 132 | 就这样。。 没了。 完成之后再看回来,这么简单。。。 全是copy。。 说个毛啊。。。。 然而,对于刚接触ExoPlayer,想要实现类似功能,而网上没啥参考的小伙伴来说,应该是有点用的,特此记录。。。。 133 | 134 | 135 | 136 | ## 结束 137 | 138 | 有帮助就点星星哟 139 | 140 | 下载源码慢慢看喔 141 | 142 | 有什么疑问或者建议欢迎issues留言噢 143 | 144 | 145 | [ExoPlayerTest小demo的Github地址](https://github.com/ChangWeiBa/AesExoPlayer "ExoPlayerTest小demo的Github地址") 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | -------------------------------------------------------------------------------- /TestPlayerActivity.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChangWeiBa/AesExoPlayer/6c1045b6557428c111fcce3c52ce59949941c9a6/TestPlayerActivity.png -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 26 5 | buildToolsVersion "26.0.1" 6 | defaultConfig { 7 | applicationId "com.ddc.exoplayertest" 8 | minSdkVersion 15 9 | targetSdkVersion 26 10 | versionCode 1 11 | versionName "1.0" 12 | } 13 | buildTypes { 14 | release { 15 | minifyEnabled false 16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 17 | } 18 | } 19 | } 20 | 21 | dependencies { 22 | compile fileTree(dir: 'libs', include: ['*.jar']) 23 | compile 'com.android.support:appcompat-v7:26.1.0' 24 | compile 'com.android.support.constraint:constraint-layout:1.0.2' 25 | //google音视频播放框架 26 | compile 'com.google.android.exoplayer:exoplayer:r2.5.4' 27 | //butterknife 7.0之后注解适配 28 | //butterknife 29 | compile 'com.jakewharton:butterknife:8.8.1' 30 | annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1' 31 | //log工具 32 | compile 'com.jakewharton.timber:timber:4.5.1' 33 | 34 | //OkHttp+Retrofit 35 | compile 'com.squareup.okhttp3:logging-interceptor:3.4.1' 36 | compile 'com.squareup.retrofit2:retrofit:2.1.0' 37 | compile 'com.squareup.retrofit2:converter-gson:2.1.0' 38 | compile 'io.reactivex.rxjava2:rxandroid:2.0.1' 39 | 40 | } 41 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /app/src/main/assets/终于等到你.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChangWeiBa/AesExoPlayer/6c1045b6557428c111fcce3c52ce59949941c9a6/app/src/main/assets/终于等到你.mp3 -------------------------------------------------------------------------------- /app/src/main/java/com/ddc/exoplayertest/AESHelper.java: -------------------------------------------------------------------------------- 1 | package com.ddc.exoplayertest; 2 | 3 | import java.io.File; 4 | import java.io.FileInputStream; 5 | import java.io.FileNotFoundException; 6 | import java.io.FileOutputStream; 7 | import java.io.IOException; 8 | import java.security.InvalidAlgorithmParameterException; 9 | import java.security.InvalidKeyException; 10 | import java.security.NoSuchAlgorithmException; 11 | 12 | import javax.crypto.Cipher; 13 | import javax.crypto.CipherInputStream; 14 | import javax.crypto.CipherOutputStream; 15 | import javax.crypto.KeyGenerator; 16 | import javax.crypto.NoSuchPaddingException; 17 | import javax.crypto.spec.IvParameterSpec; 18 | import javax.crypto.spec.SecretKeySpec; 19 | 20 | import timber.log.Timber; 21 | 22 | /** 23 | * AES加密解密帮助类 24 | * Created by 汪常伟 on 2017/9/4. 25 | */ 26 | 27 | public class AESHelper { 28 | public static final String VIPARA = "1231231241241243"; 29 | private static final String TAG = AESHelper.class.getSimpleName(); 30 | 31 | /** 32 | * 初始化 AES Cipher 33 | * 34 | * @param sKey 35 | * @param cipherMode 36 | * @return 37 | */ 38 | private static Cipher initAESCipher(String sKey, int cipherMode) { 39 | //创建Key gen 40 | KeyGenerator keyGenerator = null; 41 | Cipher cipher = null; 42 | try { 43 | IvParameterSpec zeroIv = new IvParameterSpec(VIPARA.getBytes()); 44 | SecretKeySpec key = new SecretKeySpec(sKey.getBytes(), "AES"); 45 | cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 46 | cipher.init(cipherMode, key, zeroIv); 47 | } catch (NoSuchAlgorithmException e) { 48 | e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. 49 | } catch (NoSuchPaddingException e) { 50 | e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. 51 | } catch (InvalidKeyException e) { 52 | e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. 53 | } catch (InvalidAlgorithmParameterException e) { 54 | // TODO Auto-generated catch block 55 | e.printStackTrace(); 56 | } 57 | return cipher; 58 | } 59 | 60 | 61 | /** 62 | * 对文件进行AES加密 63 | * 64 | * @param key 65 | * @param sourceFilePath 66 | * @param destFilePath 67 | * @return 68 | */ 69 | public static File encryptFile(String key, String sourceFilePath, String destFilePath) { 70 | FileInputStream in = null; 71 | FileOutputStream out = null; 72 | File destFile = null; 73 | File sourceFile = null; 74 | try { 75 | sourceFile = new File(sourceFilePath); 76 | 77 | Timber.e( sourceFilePath + "---" + sourceFile.getAbsolutePath()); 78 | destFile = new File(destFilePath); 79 | if (sourceFile.exists() && sourceFile.isFile()) { 80 | if (!destFile.getParentFile().exists()) { 81 | destFile.getParentFile().mkdirs(); 82 | } 83 | destFile.createNewFile(); 84 | in = new FileInputStream(sourceFile); 85 | out = new FileOutputStream(destFile); 86 | Cipher cipher = initAESCipher(key, Cipher.ENCRYPT_MODE); 87 | //以加密流写入文件 88 | CipherInputStream cipherInputStream = new CipherInputStream(in, cipher); 89 | byte[] cache = new byte[1024]; 90 | int nRead = 0; 91 | while ((nRead = cipherInputStream.read(cache)) != -1) { 92 | out.write(cache, 0, nRead); 93 | out.flush(); 94 | } 95 | cipherInputStream.close(); 96 | } 97 | } catch (FileNotFoundException e) { 98 | e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. 99 | } catch (IOException e) { 100 | e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. 101 | } finally { 102 | try { 103 | if (out != null) { 104 | out.close(); 105 | } 106 | } catch (IOException e) { 107 | e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. 108 | } 109 | try { 110 | if (in != null) { 111 | in.close(); 112 | } 113 | } catch (IOException e) { 114 | e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. 115 | } 116 | } 117 | return destFile; 118 | } 119 | 120 | 121 | /** 122 | * AES方式解密文件 123 | * 124 | * @param key 125 | * @param sourceFilePath 126 | * @param destFilePath 127 | * @return 128 | */ 129 | public static File decryptFile(String key, String sourceFilePath, String destFilePath) { 130 | FileInputStream in = null; 131 | FileOutputStream out = null; 132 | File destFile = null; 133 | File sourceFile = null; 134 | try { 135 | sourceFile = new File(sourceFilePath); 136 | destFile = new File(destFilePath); 137 | if (sourceFile.exists() && sourceFile.isFile()) { 138 | if (!destFile.getParentFile().exists()) { 139 | destFile.getParentFile().mkdirs(); 140 | } 141 | destFile.createNewFile(); 142 | in = new FileInputStream(sourceFile); 143 | out = new FileOutputStream(destFile); 144 | Cipher cipher = initAESCipher(key, Cipher.DECRYPT_MODE); 145 | CipherOutputStream cipherOutputStream = new CipherOutputStream(out, cipher); 146 | byte[] buffer = new byte[1024]; 147 | int r; 148 | while ((r = in.read(buffer)) >= 0) { 149 | cipherOutputStream.write(buffer, 0, r); 150 | } 151 | cipherOutputStream.close(); 152 | } 153 | } catch (IOException e) { 154 | e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. 155 | } finally { 156 | try { 157 | if (in != null) { 158 | in.close(); 159 | } 160 | } catch (IOException e) { 161 | e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. 162 | } 163 | try { 164 | if (out != null) { 165 | out.close(); 166 | } 167 | } catch (IOException e) { 168 | e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. 169 | } 170 | } 171 | return destFile; 172 | } 173 | 174 | } 175 | -------------------------------------------------------------------------------- /app/src/main/java/com/ddc/exoplayertest/Aes128DataSource.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.ddc.exoplayertest; 17 | 18 | import android.net.Uri; 19 | 20 | import com.google.android.exoplayer2.C; 21 | import com.google.android.exoplayer2.upstream.DataSource; 22 | import com.google.android.exoplayer2.upstream.DataSourceInputStream; 23 | import com.google.android.exoplayer2.upstream.DataSpec; 24 | import com.google.android.exoplayer2.util.Assertions; 25 | 26 | import java.io.IOException; 27 | import java.security.InvalidAlgorithmParameterException; 28 | import java.security.InvalidKeyException; 29 | import java.security.Key; 30 | import java.security.NoSuchAlgorithmException; 31 | import java.security.spec.AlgorithmParameterSpec; 32 | 33 | import javax.crypto.Cipher; 34 | import javax.crypto.CipherInputStream; 35 | import javax.crypto.NoSuchPaddingException; 36 | import javax.crypto.spec.IvParameterSpec; 37 | import javax.crypto.spec.SecretKeySpec; 38 | 39 | /** 40 | * Exoplayer官方Demo的AesDataSource 41 | * A {@link DataSource} that decrypts data read from an upstream source, encrypted with AES-128 with 42 | * a 128-bit key and PKCS7 padding. 43 | *

44 | * Note that this {@link DataSource} does not support being opened from arbitrary offsets. It is 45 | * designed specifically for reading whole files as defined in an HLS media playlist. For this 46 | * reason the implementation is private to the HLS package. 47 | */ 48 | /* package */ final class Aes128DataSource implements DataSource { 49 | 50 | private final DataSource upstream; 51 | private final byte[] encryptionKey; 52 | private final byte[] encryptionIv; 53 | 54 | private CipherInputStream cipherInputStream; 55 | 56 | /** 57 | * @param upstream The upstream {@link DataSource}. 58 | * @param encryptionKey The encryption key. 59 | * @param encryptionIv The encryption initialization vector. 60 | */ 61 | public Aes128DataSource(DataSource upstream, byte[] encryptionKey, byte[] encryptionIv) { 62 | this.upstream = upstream; 63 | this.encryptionKey = encryptionKey; 64 | this.encryptionIv = encryptionIv; 65 | } 66 | 67 | @Override 68 | public long open(DataSpec dataSpec) throws IOException { 69 | Cipher cipher; 70 | try { 71 | cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); 72 | } catch (NoSuchAlgorithmException | NoSuchPaddingException e) { 73 | throw new RuntimeException(e); 74 | } 75 | 76 | Key cipherKey = new SecretKeySpec(encryptionKey, "AES"); 77 | AlgorithmParameterSpec cipherIV = new IvParameterSpec(encryptionIv); 78 | 79 | try { 80 | cipher.init(Cipher.DECRYPT_MODE, cipherKey, cipherIV); 81 | } catch (InvalidKeyException | InvalidAlgorithmParameterException e) { 82 | throw new RuntimeException(e); 83 | } 84 | 85 | cipherInputStream = new CipherInputStream( 86 | new DataSourceInputStream(upstream, dataSpec), cipher); 87 | 88 | return C.LENGTH_UNSET; 89 | } 90 | 91 | @Override 92 | public void close() throws IOException { 93 | cipherInputStream = null; 94 | upstream.close(); 95 | } 96 | 97 | @Override 98 | public int read(byte[] buffer, int offset, int readLength) throws IOException { 99 | Assertions.checkState(cipherInputStream != null); 100 | int bytesRead = cipherInputStream.read(buffer, offset, readLength); 101 | if (bytesRead < 0) { 102 | return C.RESULT_END_OF_INPUT; 103 | } 104 | return bytesRead; 105 | } 106 | 107 | @Override 108 | public Uri getUri() { 109 | return upstream.getUri(); 110 | } 111 | 112 | } 113 | -------------------------------------------------------------------------------- /app/src/main/java/com/ddc/exoplayertest/AitripDataSource.java: -------------------------------------------------------------------------------- 1 | package com.ddc.exoplayertest; 2 | 3 | import android.content.Context; 4 | import android.net.Uri; 5 | import android.util.Log; 6 | 7 | import com.google.android.exoplayer2.upstream.AssetDataSource; 8 | import com.google.android.exoplayer2.upstream.ContentDataSource; 9 | import com.google.android.exoplayer2.upstream.DataSource; 10 | import com.google.android.exoplayer2.upstream.DataSpec; 11 | import com.google.android.exoplayer2.upstream.DefaultHttpDataSource; 12 | import com.google.android.exoplayer2.upstream.FileDataSource; 13 | import com.google.android.exoplayer2.upstream.TransferListener; 14 | import com.google.android.exoplayer2.util.Assertions; 15 | import com.google.android.exoplayer2.util.Util; 16 | 17 | import java.io.IOException; 18 | import java.lang.reflect.InvocationTargetException; 19 | 20 | import timber.log.Timber; 21 | 22 | /** 23 | * 自定义的数据工厂类 24 | * Created by 汪常伟 on 2017/11/13. 25 | */ 26 | 27 | public class AitripDataSource implements DataSource { 28 | private static final String TAG = "DefaultDataSource"; 29 | 30 | private static final String SCHEME_ASSET = "asset"; 31 | private static final String SCHEME_CONTENT = "content"; 32 | private static final String SCHEME_RTMP = "rtmp"; 33 | 34 | private final Context context; 35 | private final TransferListener listener; 36 | 37 | private final DataSource baseDataSource; 38 | 39 | // Lazily initialized. 40 | private DataSource fileDataSource; 41 | private DataSource assetDataSource; 42 | private DataSource contentDataSource; 43 | private DataSource rtmpDataSource; 44 | 45 | private DataSource dataSource; 46 | private String Aikey = "1231231241241243"; 47 | 48 | 49 | /** 50 | * Constructs a new instance, optionally configured to follow cross-protocol redirects. 51 | * 52 | * @param context A context. 53 | * @param listener An optional listener. 54 | * @param userAgent The User-Agent string that should be used when requesting remote data. 55 | * @param allowCrossProtocolRedirects Whether cross-protocol redirects (i.e. redirects from HTTP 56 | * to HTTPS and vice versa) are enabled when fetching remote data. 57 | */ 58 | public AitripDataSource(Context context, TransferListener listener, 59 | String userAgent, boolean allowCrossProtocolRedirects) { 60 | this(context, listener, userAgent, DefaultHttpDataSource.DEFAULT_CONNECT_TIMEOUT_MILLIS, 61 | DefaultHttpDataSource.DEFAULT_READ_TIMEOUT_MILLIS, allowCrossProtocolRedirects); 62 | } 63 | 64 | /** 65 | * Constructs a new instance, optionally configured to follow cross-protocol redirects. 66 | * 67 | * @param context A context. 68 | * @param listener An optional listener. 69 | * @param userAgent The User-Agent string that should be used when requesting remote data. 70 | * @param connectTimeoutMillis The connection timeout that should be used when requesting remote 71 | * data, in milliseconds. A timeout of zero is interpreted as an infinite timeout. 72 | * @param readTimeoutMillis The read timeout that should be used when requesting remote data, 73 | * in milliseconds. A timeout of zero is interpreted as an infinite timeout. 74 | * @param allowCrossProtocolRedirects Whether cross-protocol redirects (i.e. redirects from HTTP 75 | * to HTTPS and vice versa) are enabled when fetching remote data. 76 | */ 77 | public AitripDataSource(Context context, TransferListener listener, 78 | String userAgent, int connectTimeoutMillis, int readTimeoutMillis, 79 | boolean allowCrossProtocolRedirects) { 80 | this(context, listener, 81 | new DefaultHttpDataSource(userAgent, null, listener, connectTimeoutMillis, 82 | readTimeoutMillis, allowCrossProtocolRedirects, null)); 83 | } 84 | 85 | /** 86 | * Constructs a new instance that delegates to a provided {@link DataSource} for URI schemes other 87 | * than file, asset and content. 88 | * 89 | * @param context A context. 90 | * @param listener An optional listener. 91 | * @param baseDataSource A {@link DataSource} to use for URI schemes other than file, asset and 92 | * content. This {@link DataSource} should normally support at least http(s). 93 | */ 94 | public AitripDataSource(Context context, TransferListener listener, 95 | DataSource baseDataSource) { 96 | this.context = context.getApplicationContext(); 97 | this.listener = listener; 98 | this.baseDataSource = Assertions.checkNotNull(baseDataSource); 99 | } 100 | 101 | @Override 102 | public long open(DataSpec dataSpec) throws IOException { 103 | Assertions.checkState(dataSource == null); 104 | // Choose the correct source for the scheme. 105 | //选择正确的数据源方案 106 | String scheme = dataSpec.uri.getScheme(); 107 | //如果URI是一个本地文件路径或本地文件的引用。 108 | Timber.e("解密:000000," + scheme + ",path:" + dataSpec.uri.getPath()); 109 | if (Util.isLocalFileUri(dataSpec.uri)) { 110 | //如果路径尾包含aitrip的文件名,使用解密类 111 | if (dataSpec.uri.getPath().endsWith(".aitrip")) { 112 | Aes128DataSource aes128DataSource = 113 | new Aes128DataSource(getFileDataSource(), Aikey.getBytes(), Aikey.getBytes()); 114 | dataSource = aes128DataSource; 115 | } else {//否则,正常解析mp3 116 | if (dataSpec.uri.getPath().startsWith("/android_asset/")) { 117 | dataSource = getAssetDataSource(); 118 | } else { 119 | dataSource = getFileDataSource(); 120 | } 121 | } 122 | } else if (SCHEME_ASSET.equals(scheme)) { 123 | dataSource = getAssetDataSource(); 124 | } else if (SCHEME_CONTENT.equals(scheme)) { 125 | dataSource = getContentDataSource(); 126 | } else if (SCHEME_RTMP.equals(scheme)) { 127 | dataSource = getRtmpDataSource(); 128 | } else { 129 | dataSource = baseDataSource; 130 | } 131 | // Open the source and return. 132 | return dataSource.open(dataSpec); 133 | } 134 | 135 | @Override 136 | public int read(byte[] buffer, int offset, int readLength) throws IOException { 137 | return dataSource.read(buffer, offset, readLength); 138 | } 139 | 140 | @Override 141 | public Uri getUri() { 142 | return dataSource == null ? null : dataSource.getUri(); 143 | } 144 | 145 | @Override 146 | public void close() throws IOException { 147 | if (dataSource != null) { 148 | try { 149 | dataSource.close(); 150 | } finally { 151 | dataSource = null; 152 | } 153 | } 154 | } 155 | 156 | private DataSource getFileDataSource() { 157 | if (fileDataSource == null) { 158 | Timber.e("解密:666666666,"); 159 | fileDataSource = new FileDataSource(listener); 160 | } 161 | return fileDataSource; 162 | } 163 | 164 | private DataSource getAssetDataSource() { 165 | if (assetDataSource == null) { 166 | assetDataSource = new AssetDataSource(context, listener); 167 | } 168 | return assetDataSource; 169 | } 170 | 171 | private DataSource getContentDataSource() { 172 | if (contentDataSource == null) { 173 | contentDataSource = new ContentDataSource(context, listener); 174 | } 175 | return contentDataSource; 176 | } 177 | 178 | private DataSource getRtmpDataSource() { 179 | if (rtmpDataSource == null) { 180 | try { 181 | Class clazz = Class.forName("com.google.android.exoplayer2.ext.rtmp.RtmpDataSource"); 182 | rtmpDataSource = (DataSource) clazz.getDeclaredConstructor().newInstance(); 183 | } catch (ClassNotFoundException e) { 184 | Log.w(TAG, "Attempting to play RTMP stream without depending on the RTMP extension"); 185 | } catch (InstantiationException e) { 186 | Log.e(TAG, "Error instantiating RtmpDataSource", e); 187 | } catch (IllegalAccessException e) { 188 | Log.e(TAG, "Error instantiating RtmpDataSource", e); 189 | } catch (NoSuchMethodException e) { 190 | Log.e(TAG, "Error instantiating RtmpDataSource", e); 191 | } catch (InvocationTargetException e) { 192 | Log.e(TAG, "Error instantiating RtmpDataSource", e); 193 | } 194 | if (rtmpDataSource == null) { 195 | rtmpDataSource = baseDataSource; 196 | } 197 | } 198 | return rtmpDataSource; 199 | } 200 | } 201 | -------------------------------------------------------------------------------- /app/src/main/java/com/ddc/exoplayertest/AitripDataSourceFactory.java: -------------------------------------------------------------------------------- 1 | package com.ddc.exoplayertest; 2 | 3 | import android.content.Context; 4 | 5 | import com.google.android.exoplayer2.upstream.DataSource; 6 | import com.google.android.exoplayer2.upstream.DefaultDataSource; 7 | import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory; 8 | import com.google.android.exoplayer2.upstream.TransferListener; 9 | 10 | /** 11 | * 自定义资源工厂 12 | * Created by 汪常伟 on 2017/11/13. 13 | */ 14 | 15 | public class AitripDataSourceFactory implements DataSource.Factory { 16 | 17 | private final Context context; 18 | private final TransferListener listener; 19 | private final DataSource.Factory baseDataSourceFactory; 20 | 21 | /** 22 | * @param context A context. 23 | * @param userAgent The User-Agent string that should be used. 24 | */ 25 | public AitripDataSourceFactory(Context context, String userAgent) { 26 | this(context, userAgent, null); } 27 | 28 | /** 29 | * @param context A context. 30 | * @param userAgent The User-Agent string that should be used. 31 | * @param listener An optional listener. 32 | */ 33 | public AitripDataSourceFactory(Context context, String userAgent, 34 | TransferListener listener) { 35 | this(context, listener, new DefaultHttpDataSourceFactory(userAgent, listener)); 36 | } 37 | 38 | /** 39 | * @param context A context. 40 | * @param listener An optional listener. 41 | * @param baseDataSourceFactory A {@link DataSource.Factory} to be used to create a base {@link DataSource} 42 | * for {@link DefaultDataSource}. 43 | * @see DefaultDataSource#DefaultDataSource(Context, TransferListener, DataSource) 44 | */ 45 | public AitripDataSourceFactory(Context context, TransferListener listener, 46 | DataSource.Factory baseDataSourceFactory) { 47 | this.context = context.getApplicationContext(); 48 | this.listener = listener; 49 | this.baseDataSourceFactory = baseDataSourceFactory; 50 | } 51 | 52 | @Override 53 | public AitripDataSource createDataSource() { 54 | return new AitripDataSource(context, listener, baseDataSourceFactory.createDataSource()); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /app/src/main/java/com/ddc/exoplayertest/AppContext.java: -------------------------------------------------------------------------------- 1 | package com.ddc.exoplayertest; 2 | 3 | import android.app.Application; 4 | import android.content.Context; 5 | import android.os.Build; 6 | import android.os.Environment; 7 | import android.os.StrictMode; 8 | 9 | import com.google.android.exoplayer2.util.Util; 10 | 11 | import java.io.File; 12 | 13 | import timber.log.Timber; 14 | 15 | /** 16 | * Created by wang on 2016/12/26 17 | */ 18 | public class AppContext extends Application { 19 | 20 | private static AppContext instance; 21 | private String userAgent; 22 | private static String FildDir =Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + 23 | "ExoPlayerTest"; 24 | 25 | 26 | @Override 27 | protected void attachBaseContext(Context base) { 28 | super.attachBaseContext(base); 29 | } 30 | 31 | @Override 32 | public void onCreate() { 33 | super.onCreate(); 34 | 35 | instance = this; 36 | userAgent = Util.getUserAgent(this, "ExoPlayerDemo"); 37 | 38 | 39 | //在这里先使用Timber.plant注册一个Tree,然后调用静态的.d .v 去使用 40 | if (BuildConfig.DEBUG) { 41 | Timber.plant(new Timber.DebugTree()); 42 | } 43 | 44 | 45 | //Android N 文件权限 46 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { 47 | StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder(); 48 | StrictMode.setVmPolicy(builder.build()); 49 | } 50 | 51 | 52 | 53 | } 54 | 55 | public static Context getAppContext() { 56 | return instance; 57 | } 58 | 59 | public static Context getContext() { 60 | return instance; 61 | } 62 | 63 | public static String getFildDir() { 64 | return FildDir; 65 | } 66 | 67 | 68 | @Override 69 | public void onTerminate() { 70 | super.onTerminate(); 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /app/src/main/java/com/ddc/exoplayertest/TestPlayerActivity.java: -------------------------------------------------------------------------------- 1 | package com.ddc.exoplayertest; 2 | 3 | import android.Manifest; 4 | import android.content.Context; 5 | import android.content.Intent; 6 | import android.graphics.Color; 7 | import android.media.session.PlaybackState; 8 | import android.net.Uri; 9 | import android.os.Bundle; 10 | import android.os.Environment; 11 | import android.os.Handler; 12 | import android.os.Message; 13 | import android.support.v7.app.AppCompatActivity; 14 | import android.view.View; 15 | import android.widget.Button; 16 | import android.widget.ImageView; 17 | import android.widget.LinearLayout; 18 | import android.widget.SeekBar; 19 | import android.widget.TextView; 20 | 21 | import com.ddc.exoplayertest.permission.OnPermissionCallback; 22 | import com.ddc.exoplayertest.permission.PermissionManager; 23 | import com.google.android.exoplayer2.C; 24 | import com.google.android.exoplayer2.DefaultLoadControl; 25 | import com.google.android.exoplayer2.ExoPlaybackException; 26 | import com.google.android.exoplayer2.ExoPlayer; 27 | import com.google.android.exoplayer2.ExoPlayerFactory; 28 | import com.google.android.exoplayer2.PlaybackParameters; 29 | import com.google.android.exoplayer2.SimpleExoPlayer; 30 | import com.google.android.exoplayer2.Timeline; 31 | import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory; 32 | import com.google.android.exoplayer2.extractor.ExtractorsFactory; 33 | import com.google.android.exoplayer2.source.ConcatenatingMediaSource; 34 | import com.google.android.exoplayer2.source.ExtractorMediaSource; 35 | import com.google.android.exoplayer2.source.MediaSource; 36 | import com.google.android.exoplayer2.source.TrackGroupArray; 37 | import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection; 38 | import com.google.android.exoplayer2.trackselection.DefaultTrackSelector; 39 | import com.google.android.exoplayer2.trackselection.TrackSelection; 40 | import com.google.android.exoplayer2.trackselection.TrackSelectionArray; 41 | import com.google.android.exoplayer2.trackselection.TrackSelector; 42 | import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter; 43 | import com.google.android.exoplayer2.upstream.FileDataSource; 44 | import com.google.android.exoplayer2.util.Util; 45 | 46 | import java.io.File; 47 | import java.lang.ref.WeakReference; 48 | import java.util.concurrent.ExecutorService; 49 | import java.util.concurrent.Executors; 50 | 51 | import butterknife.BindView; 52 | import butterknife.ButterKnife; 53 | import timber.log.Timber; 54 | 55 | /** 56 | * 音频播放测试demo,主要用于直接解密播放AES加密的音频流,利用官方类自定义了DataSource 57 | */ 58 | public class TestPlayerActivity extends AppCompatActivity implements View.OnClickListener { 59 | 60 | private static final String TAG = "TestPlayerActivity"; 61 | @BindView(R.id.start_play) 62 | ImageView startPlay; 63 | @BindView(R.id.already_player) 64 | TextView alreadyPlayer; 65 | @BindView(R.id.seek_bar) 66 | SeekBar seekBar; 67 | @BindView(R.id.all_player_time) 68 | TextView allPlayerTime; 69 | @BindView(R.id.play_linear) 70 | LinearLayout playLinear; 71 | @BindView(R.id.bt_encrypt) 72 | Button btEncrypt; 73 | @BindView(R.id.bt_decrypt) 74 | Button btDecrypt; 75 | @BindView(R.id.bt_encryplay) 76 | Button btEncryplay; 77 | private ExtractorMediaSource videoSource; 78 | private String url = "https://storage.googleapis.com/exoplayer-test-media-0/play.mp3"; 79 | 80 | private static final int UP_TIME = 0;//更新播放时间 81 | private boolean screenFlag = false;//全屏标记 82 | private SimpleExoPlayer player; 83 | private boolean playFlag = false;//播放状态 84 | private ExecutorService executors = Executors.newSingleThreadExecutor(); 85 | private final MyHandler myHandler = new MyHandler(this); 86 | Uri playerUri = Uri.parse("https://storage.googleapis.com/exoplayer-test-media-0/play.mp3"); 87 | private ExtractorsFactory extractorsFactory; 88 | private Timeline.Window window; 89 | private int rewindMs = 2;//快退 90 | private int fastForwardMs = 2;//快进 91 | private AitripDataSourceFactory aitripFactory; 92 | private String Aikey = "1231231241241243"; 93 | private static final String deng = "/sdcard/Music/终于等到你.mp3"; 94 | 95 | private static String FildDir = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + 96 | "ExoPlayerTest"; 97 | 98 | 99 | public static void start(Context context) { 100 | Intent starter = new Intent(context, TestPlayerActivity.class); 101 | context.startActivity(starter); 102 | } 103 | 104 | 105 | @Override 106 | protected void onCreate(Bundle savedInstanceState) { 107 | super.onCreate(savedInstanceState); 108 | setContentView(R.layout.activity_test_player); 109 | ButterKnife.bind(this); 110 | btDecrypt.setOnClickListener(this); 111 | btEncrypt.setOnClickListener(this); 112 | allPlayerTime.setOnClickListener(this); 113 | startPlay.setOnClickListener(this); 114 | btEncryplay.setOnClickListener(this); 115 | 116 | if (BuildConfig.DEBUG) { 117 | Timber.plant(new Timber.DebugTree()); 118 | } 119 | 120 | 121 | initData(); 122 | initPlayer(deng); 123 | 124 | 125 | } 126 | 127 | protected void initData() { 128 | PermissionManager.instance() 129 | .with(this) 130 | .request(new OnPermissionCallback() { 131 | @Override 132 | public void onRequestAllow(String permissionName) { 133 | } 134 | 135 | @Override 136 | public void onRequestRefuse(String permissionName) { 137 | } 138 | 139 | @Override 140 | public void onRequestNoAsk(String permissionName) { 141 | Timber.e("不在询问了"); 142 | } 143 | }, 144 | Manifest.permission.READ_EXTERNAL_STORAGE, 145 | Manifest.permission.WRITE_EXTERNAL_STORAGE); 146 | } 147 | 148 | private void initPlayer(String url) { 149 | // 1.创建一个默认TrackSelector,测量播放过程中的带宽。 如果不需要,可以为null。 150 | DefaultBandwidthMeter bandwidthMeter = new DefaultBandwidthMeter(); 151 | //从MediaSource中选出media提供给可用的Render S来渲染,在创建播放器时被注入 152 | TrackSelection.Factory videoTrackSelectionFactory = 153 | new AdaptiveTrackSelection.Factory(bandwidthMeter); 154 | TrackSelector trackSelector = 155 | new DefaultTrackSelector(videoTrackSelectionFactory); 156 | // 2.创建一个默认的LoadControl 157 | //Create a default LoadControl 控制MediaSource缓存media 158 | DefaultLoadControl loadControl = new DefaultLoadControl(); 159 | // BufferingLoadControl bufferingLoadControl = new BufferingLoadControl(); 160 | //生成加载媒体数据的DataSource实例。 161 | // dataSourceFactory = new DefaultDataSourceFactory(this, 162 | // Util.getUserAgent(this, "aitrip"), bandwidthMeter); 163 | //自定义解密工厂 164 | aitripFactory = new AitripDataSourceFactory(this, 165 | Util.getUserAgent(this, "aitrip"), bandwidthMeter); 166 | extractorsFactory = new DefaultExtractorsFactory(); 167 | // factory = new DiyExtractorsFactory(); 168 | FileDataSource fileDataSource = new FileDataSource(); 169 | //test mp3 170 | // url = "https://storage.googleapis.com/exoplayer-test-media-0/play.mp3"; 171 | // MediaSource代表要播放的媒体。 172 | videoSource = new ExtractorMediaSource(Uri.parse(url), 173 | aitripFactory, extractorsFactory, null, null); 174 | // 3.创建播放器 175 | player = ExoPlayerFactory.newSimpleInstance(this, trackSelector, loadControl); 176 | 177 | //SimpleExoPlayerView simpleExoPlayerView = (SimpleExoPlayerView) findViewById(R.id.exo_player); 178 | //设置监听器 179 | player.addListener(eventListener); 180 | //装载多个资源 181 | MediaSource[] mediaSources = new MediaSource[1]; 182 | // mediaSources[0] = buildMediaSource(Uri.parse(huai), ""); 183 | // mediaSources[1] = buildMediaSource(Uri.parse(deng), ""); 184 | mediaSources[0] = buildMediaSource(Uri.parse(deng), ""); 185 | // mediaSources[2] = buildMediaSource(playerUri, ""); 186 | // mediaSources[3] = buildMediaSource(Uri.parse(deng), ""); 187 | ConcatenatingMediaSource mediaSource = new ConcatenatingMediaSource(mediaSources); 188 | 189 | //设置资源 190 | player.prepare(mediaSource); 191 | window = new Timeline.Window(); 192 | } 193 | 194 | //播放事件监听 195 | private ExoPlayer.EventListener eventListener = new ExoPlayer.EventListener() { 196 | @Override 197 | public void onTimelineChanged(Timeline timeline, Object manifest) { 198 | Timber.e("播放: onTimelineChanged 周期总数 " + timeline); 199 | } 200 | 201 | @Override 202 | public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) { 203 | Timber.e("播放: TrackGroupArray "); 204 | } 205 | 206 | @Override 207 | public void onLoadingChanged(boolean isLoading) { 208 | Timber.e("播放: onLoadingChanged " + player.getBufferedPosition()); 209 | //设置二级进度条 210 | seekBar.setSecondaryProgress((int) (player.getBufferedPosition() / 1000)); 211 | } 212 | 213 | @Override 214 | public void onPlayerStateChanged(boolean playWhenReady, int playbackState) { 215 | Timber.e("onPlayerStateChanged: playWhenReady = " + String.valueOf(playWhenReady) 216 | + " playbackState = " + playbackState); 217 | switch (playbackState) { 218 | case PlaybackState.STATE_PLAYING: 219 | //初始化播放点击事件并设置总时长 220 | initPlayVideo(); 221 | Timber.e("播放状态: 准备 playing"); 222 | break; 223 | 224 | case PlaybackState.STATE_BUFFERING: 225 | Timber.e("播放状态: 缓存完成 playing"); 226 | break; 227 | 228 | case PlaybackState.STATE_CONNECTING: 229 | Timber.e("播放状态: 连接 CONNECTING"); 230 | break; 231 | 232 | case PlaybackState.STATE_ERROR://错误 233 | Timber.e("播放状态: 错误 STATE_ERROR"); 234 | startPlay.setBackgroundColor(Color.WHITE); 235 | ToastUtil.showShort("播放错误"); 236 | break; 237 | 238 | case PlaybackState.STATE_FAST_FORWARDING: 239 | Timber.e("播放状态: 快速传递,播放完毕"); 240 | 241 | pausePlay();//暂停播放 242 | break; 243 | 244 | case PlaybackState.STATE_NONE: 245 | Timber.e("播放状态: 无 STATE_NONE"); 246 | break; 247 | 248 | case PlaybackState.STATE_PAUSED: 249 | Timber.e("播放状态: 暂停 PAUSED"); 250 | break; 251 | 252 | case PlaybackState.STATE_REWINDING: 253 | Timber.e("播放状态: 倒回 REWINDING"); 254 | break; 255 | 256 | case PlaybackState.STATE_SKIPPING_TO_NEXT: 257 | Timber.e("播放状态: 跳到下一个"); 258 | break; 259 | 260 | case PlaybackState.STATE_SKIPPING_TO_PREVIOUS: 261 | Timber.e("播放状态: 跳到上一个"); 262 | break; 263 | 264 | case PlaybackState.STATE_SKIPPING_TO_QUEUE_ITEM: 265 | Timber.e("播放状态: 跳到指定的Item"); 266 | break; 267 | 268 | case PlaybackState.STATE_STOPPED: 269 | Timber.e("播放状态: 停止的 STATE_STOPPED"); 270 | break; 271 | 272 | 273 | } 274 | } 275 | 276 | @Override 277 | public void onRepeatModeChanged(int repeatMode) { 278 | Timber.e("播放: onRepeatModeChanged "); 279 | } 280 | 281 | @Override 282 | public void onPlayerError(ExoPlaybackException error) { 283 | Timber.e("播放: onPlayerError "); 284 | } 285 | 286 | @Override 287 | public void onPositionDiscontinuity() { 288 | Timber.e("播放: onPositionDiscontinuity "); 289 | } 290 | 291 | @Override 292 | public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) { 293 | Timber.e("播放: onPlaybackParametersChanged "); 294 | } 295 | }; 296 | 297 | //初始化播放事件 298 | private void initPlayVideo() { 299 | allPlayerTime.setText(TimeUtils.secToTime((int) (player.getDuration() / 1000))); 300 | //设置总时长 301 | seekBar.setMax((int) (player.getDuration() / 100)); 302 | seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { 303 | @Override 304 | public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { 305 | } 306 | 307 | @Override 308 | public void onStartTrackingTouch(SeekBar seekBar) { 309 | } 310 | 311 | @Override 312 | public void onStopTrackingTouch(SeekBar seekBar) { 313 | //是暂停的开始播放 314 | if (!player.getPlayWhenReady()) { 315 | continuePlay();//继续播放 316 | } 317 | player.seekTo(seekBar.getProgress() * 1000); 318 | } 319 | }); 320 | 321 | //播放按钮 322 | startPlay.setOnClickListener(new View.OnClickListener() { 323 | @Override 324 | public void onClick(View v) { 325 | if (player.getPlayWhenReady()) { 326 | pausePlay();//暂停播放 327 | } else { 328 | continuePlay();//继续播放 329 | } 330 | } 331 | }); 332 | 333 | } 334 | 335 | 336 | //暂停播放 337 | private void pausePlay() { 338 | player.setPlayWhenReady(false); 339 | startPlay.setBackgroundColor(Color.WHITE); 340 | playFlag = false; 341 | } 342 | 343 | //继续播放 344 | private void continuePlay() { 345 | player.setPlayWhenReady(true); 346 | startPlay.setBackgroundColor(Color.RED); 347 | //开始读取进度 348 | playFlag = true; 349 | executors.execute(runnable); 350 | } 351 | 352 | @Override 353 | public void onClick(View view) { 354 | switch (view.getId()) { 355 | case R.id.bt_encrypt://加密 356 | AESHelper.encryptFile(Aikey, deng, FildDir + "/" + "终于等到你.mp3.aitrip"); 357 | break; 358 | 359 | case R.id.bt_encryplay://解密播放,自定义路径 360 | reLoadSourcePlay(FildDir + "/" + "终于等到你.mp3.aitrip"); 361 | break; 362 | 363 | case R.id.already_player://播放进度时间,点击上一首 364 | previous(); 365 | 366 | break; 367 | case R.id.all_player_time://播放总时间,点击进入下一首 368 | next(); 369 | break; 370 | 371 | } 372 | } 373 | 374 | private static final long MAX_POSITION_FOR_SEEK_TO_PREVIOUS = 3000; 375 | 376 | /** 377 | * 上一首 378 | */ 379 | private void previous() { 380 | Timeline timeline = player.getCurrentTimeline(); 381 | if (timeline.isEmpty()) { 382 | return; 383 | } 384 | int windowIndex = player.getCurrentWindowIndex(); 385 | timeline.getWindow(windowIndex, window); 386 | int previousWindowIndex = timeline.getPreviousWindowIndex(windowIndex, player.getRepeatMode()); 387 | Timber.e("previousWindowIndex:" + previousWindowIndex); 388 | Timber.e("getCurrentPosition:" + player.getCurrentPosition()); 389 | Timber.e("isDynamic:" + window.isDynamic); 390 | Timber.e("isSeekable:" + window.isSeekable); 391 | Timber.e("TIME_UNSET:" + C.TIME_UNSET); 392 | Timber.e("TIME_UNSET:" + C.TIME_UNSET); 393 | if (previousWindowIndex != C.INDEX_UNSET) { 394 | player.seekTo(previousWindowIndex, C.TIME_UNSET); 395 | } else { 396 | Timber.e("seekTo(0):"); 397 | Timber.e("已经是第一首"); 398 | // player.seekTo(0); 399 | } 400 | } 401 | 402 | 403 | /** 404 | * 下一首 405 | */ 406 | private void next() { 407 | Timeline timeline = player.getCurrentTimeline(); 408 | if (timeline.isEmpty()) { 409 | return; 410 | } 411 | 412 | int windowIndex = player.getCurrentWindowIndex(); 413 | Timber.e("windowIndex:" + windowIndex); 414 | int nextWindowIndex = timeline.getNextWindowIndex(windowIndex, player.getRepeatMode()); 415 | Timber.e("nextWindowIndex:" + nextWindowIndex); 416 | Timber.e("isDynamic:" + window.isDynamic); 417 | Timber.e("TIME_UNSET:" + C.TIME_UNSET); 418 | if (nextWindowIndex != C.INDEX_UNSET) { 419 | player.seekTo(nextWindowIndex, C.TIME_UNSET); 420 | } else if (timeline.getWindow(windowIndex, window, false).isDynamic) { 421 | player.seekTo(windowIndex, C.TIME_UNSET); 422 | Timber.e("已经最后一首"); 423 | 424 | } 425 | } 426 | 427 | private MediaSource buildMediaSource(Uri uri, String overrideExtension) { 428 | return new ExtractorMediaSource(uri, aitripFactory, extractorsFactory, 429 | null, null); 430 | } 431 | 432 | /** 433 | * 快退 434 | */ 435 | private void rewind() { 436 | if (rewindMs <= 0) { 437 | return; 438 | } 439 | player.seekTo(Math.max(player.getCurrentPosition() - rewindMs, 0)); 440 | } 441 | 442 | /** 443 | * 快进 444 | */ 445 | private void fastForward() { 446 | if (fastForwardMs <= 0) { 447 | return; 448 | } 449 | long durationMs = player.getDuration(); 450 | long seekPositionMs = player.getCurrentPosition() + fastForwardMs; 451 | if (durationMs != C.TIME_UNSET) { 452 | seekPositionMs = Math.min(seekPositionMs, durationMs); 453 | } 454 | player.seekTo(seekPositionMs); 455 | } 456 | 457 | /** 458 | * 重载资源 459 | * 460 | * @param url 461 | */ 462 | private void reLoadSourcePlay(String url) { 463 | Timber.e("重载资源file1---:" + url); 464 | //重载资源 465 | videoSource.releaseSource(); 466 | seekBar.setMax(0); 467 | seekBar.setProgress(0); 468 | allPlayerTime.setText("00:00"); 469 | ExtractorMediaSource extractorMediaSource = 470 | new ExtractorMediaSource(Uri.parse(url), aitripFactory, 471 | extractorsFactory, null, null); 472 | player.prepare(extractorMediaSource); 473 | //设置文字 474 | // allPlayerTime.setText(TimeUtils.secToTime((int) (player.getDuration() / 1000))); 475 | //设置总时长 476 | // seekBar.setMax((int) (player.getDuration() / 100)); 477 | continuePlay();//开始播放 478 | } 479 | 480 | 481 | private static class MyHandler extends Handler { 482 | private final WeakReference mActivity; 483 | 484 | private MyHandler(TestPlayerActivity mActivity) { 485 | this.mActivity = new WeakReference<>(mActivity); 486 | } 487 | 488 | @Override 489 | public void handleMessage(Message msg) { 490 | if (mActivity.get() == null) { 491 | return; 492 | } 493 | if (msg.what == UP_TIME) { 494 | //设置播放进度 495 | TestPlayerActivity videoActivity = mActivity.get(); 496 | videoActivity.seekBar.setProgress(msg.arg2); 497 | 498 | } 499 | } 500 | } 501 | 502 | //开启线程读取进度 503 | private Runnable runnable = new Runnable() { 504 | @Override 505 | public void run() { 506 | while (playFlag) { 507 | Message msg = new Message(); 508 | msg.what = UP_TIME; 509 | //获取播放时间 510 | msg.arg1 = (int) (player.getCurrentPosition() / 1000); 511 | msg.arg2 = (int) (player.getCurrentPosition() / 100); 512 | // Timber.e("player---:"+player.getCurrentPosition()); 513 | // Timber.e("arg1-----:"+msg.arg1); 514 | // Timber.e("arg222---:"+msg.arg2); 515 | myHandler.sendMessage(msg); 516 | try { 517 | Thread.sleep(100); 518 | } catch (InterruptedException e) { 519 | e.printStackTrace(); 520 | } 521 | } 522 | } 523 | }; 524 | 525 | 526 | @Override 527 | protected void onDestroy() { 528 | super.onDestroy(); 529 | //释放资源 530 | if (player != null) { 531 | playFlag = false;//停止线程 532 | executors.shutdown(); 533 | player.stop(); 534 | player.release(); 535 | player = null; 536 | videoSource.releaseSource(); 537 | aitripFactory = null; 538 | extractorsFactory = null; 539 | } 540 | myHandler.removeCallbacksAndMessages(null); 541 | } 542 | 543 | 544 | } 545 | -------------------------------------------------------------------------------- /app/src/main/java/com/ddc/exoplayertest/TimeUtils.java: -------------------------------------------------------------------------------- 1 | package com.ddc.exoplayertest; 2 | 3 | import java.text.ParseException; 4 | import java.text.SimpleDateFormat; 5 | import java.util.Date; 6 | 7 | /** 8 | * Created by QYBM_Android_two on 2017/1/17. 9 | * 时间工具类 10 | */ 11 | 12 | public class TimeUtils { 13 | //将时间转换为时间戳 14 | public static String dateToStamp(String s)throws ParseException 15 | { 16 | String res; 17 | SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 18 | Date date = simpleDateFormat.parse(s); 19 | long ts = date.getTime(); 20 | res = String.valueOf(ts); 21 | return res; 22 | } 23 | //将时间戳转换为时间 24 | public static String stampToDate(String s) 25 | { 26 | String res; 27 | SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 28 | long lt = new Long(s); 29 | Date date = new Date(lt); 30 | res = simpleDateFormat.format(date); 31 | return res; 32 | } 33 | //将时间戳转换为时间 34 | public static String stampToDates(String s) 35 | { 36 | String res; 37 | SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); 38 | long lt = new Long(s); 39 | Date date = new Date(lt); 40 | res = simpleDateFormat.format(date); 41 | return res; 42 | } 43 | //将秒转为 天 小时 分钟 44 | public static String secToTime(int time) { 45 | int day; 46 | int hour; 47 | int minute; 48 | int second; 49 | if (time <= 0) 50 | { 51 | return "00:00"; 52 | } 53 | else 54 | { 55 | minute = time / 60;//还有--分钟 56 | if (minute < 60) { 57 | second = time % 60; 58 | return unitFormat(minute) + ":" + unitFormat(second)+""; 59 | } 60 | 61 | hour = minute / 60;//还有--小时 62 | if (hour < 24) 63 | { 64 | minute = minute % 60; 65 | second = time - hour * 3600 - minute * 60; 66 | return unitFormat(hour) + ":" + unitFormat(minute) + ":" + unitFormat(second)+":"; 67 | } 68 | 69 | day = hour/24;//还有--天 70 | hour = hour % 24;//剩余多少小时 71 | minute = minute - day * 24 * 60 - hour * 60;//剩余的分钟数 72 | return unitFormat(day)+"天"+ unitFormat(hour) + "小时" + unitFormat(minute)+"分钟"; 73 | } 74 | } 75 | 76 | private static String unitFormat(int i) { 77 | String retStr; 78 | if (i >= 0 && i < 10) 79 | retStr = "0" + Integer.toString(i); 80 | else 81 | retStr = "" + i; 82 | return retStr; 83 | } 84 | 85 | public static void main(String[] args) { 86 | System.out.println(secToTime(600000)); 87 | } 88 | } 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | -------------------------------------------------------------------------------- /app/src/main/java/com/ddc/exoplayertest/ToastUtil.java: -------------------------------------------------------------------------------- 1 | package com.ddc.exoplayertest; 2 | 3 | import android.widget.Toast; 4 | 5 | 6 | public class ToastUtil { 7 | 8 | public static boolean isShow = true; 9 | 10 | private static String oldMsg; 11 | protected static Toast toast = null; 12 | private static long oneTime = 0; 13 | private static long twoTime = 0; 14 | 15 | /** 16 | * 短时间显示Toast 17 | * 18 | * @param message 19 | */ 20 | public static void showShort(CharSequence message) { 21 | if (toast == null) { 22 | toast = Toast.makeText(AppContext.getContext(), message, Toast.LENGTH_SHORT); 23 | toast.show(); 24 | oneTime = System.currentTimeMillis(); 25 | } else { 26 | twoTime = System.currentTimeMillis(); 27 | if (message.equals(oldMsg)) { 28 | if (twoTime - oneTime > Toast.LENGTH_SHORT) { 29 | toast.show(); 30 | } 31 | } else { 32 | oldMsg = message.toString(); 33 | toast.setText(message.toString()); 34 | toast.show(); 35 | } 36 | } 37 | oneTime = twoTime; 38 | } 39 | 40 | /** 41 | * 长时间显示Toast 42 | * 43 | * @param message 44 | */ 45 | public static void showLong(CharSequence message) { 46 | if (toast == null) { 47 | toast = Toast.makeText(AppContext.getAppContext(), message, Toast.LENGTH_SHORT); 48 | toast.show(); 49 | oneTime = System.currentTimeMillis(); 50 | } else { 51 | twoTime = System.currentTimeMillis(); 52 | if (message.equals(oldMsg)) { 53 | if (twoTime - oneTime > Toast.LENGTH_SHORT) { 54 | toast.show(); 55 | } 56 | } else { 57 | oldMsg = message.toString(); 58 | toast.setText(message.toString()); 59 | toast.show(); 60 | } 61 | } 62 | oneTime = twoTime; 63 | } 64 | 65 | /** 66 | * 自定义显示Toast时间 67 | * 68 | * @param message 69 | * @param duration 70 | */ 71 | public static void show(CharSequence message, int duration) { 72 | if (toast == null) { 73 | toast = Toast.makeText(AppContext.getAppContext(), message, duration); 74 | toast.show(); 75 | oneTime = System.currentTimeMillis(); 76 | } else { 77 | twoTime = System.currentTimeMillis(); 78 | if (message.equals(oldMsg)) { 79 | if (twoTime - oneTime > duration) { 80 | toast.show(); 81 | } 82 | } else { 83 | oldMsg = message.toString(); 84 | toast.setText(message.toString()); 85 | toast.show(); 86 | } 87 | } 88 | oneTime = twoTime; 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /app/src/main/java/com/ddc/exoplayertest/permission/OnPermissionCallback.java: -------------------------------------------------------------------------------- 1 | package com.ddc.exoplayertest.permission; 2 | 3 | /** 4 | * @Description: 申请权限回调 5 | * @author: DAWI 6 | * @date: 2017-04-21 11:24 7 | */ 8 | public interface OnPermissionCallback { 9 | //允许 10 | void onRequestAllow(String permissionName); 11 | //拒绝 12 | void onRequestRefuse(String permissionName); 13 | //不在询问 14 | void onRequestNoAsk(String permissionName); 15 | } 16 | -------------------------------------------------------------------------------- /app/src/main/java/com/ddc/exoplayertest/permission/Permission.java: -------------------------------------------------------------------------------- 1 | package com.ddc.exoplayertest.permission; 2 | 3 | /** 4 | * @Description: 权限实体类 5 | * @author: DAWI 6 | * @date: 2017-04-19 20:14 7 | */ 8 | public class Permission { 9 | //权限名称 10 | public final String name; 11 | //是否授予权限 12 | public final boolean granted; 13 | //是否显示请求权限理由 14 | public final boolean shouldShowRequestPermissionRationale; 15 | 16 | public Permission(String name, boolean granted) { 17 | this(name, granted, false); 18 | } 19 | 20 | public Permission(String name, boolean granted, boolean shouldShowRequestPermissionRationale) { 21 | this.name = name; 22 | this.granted = granted; 23 | this.shouldShowRequestPermissionRationale = shouldShowRequestPermissionRationale; 24 | } 25 | 26 | @Override 27 | @SuppressWarnings("SimplifiableIfStatement") 28 | public boolean equals(final Object o) { 29 | if (this == o) return true; 30 | if (o == null || getClass() != o.getClass()) return false; 31 | 32 | final Permission that = (Permission) o; 33 | 34 | if (granted != that.granted) return false; 35 | if (shouldShowRequestPermissionRationale != that.shouldShowRequestPermissionRationale) 36 | return false; 37 | return name.equals(that.name); 38 | } 39 | 40 | @Override 41 | public int hashCode() { 42 | int result = name.hashCode(); 43 | result = 31 * result + (granted ? 1 : 0); 44 | result = 31 * result + (shouldShowRequestPermissionRationale ? 1 : 0); 45 | return result; 46 | } 47 | 48 | @Override 49 | public String toString() { 50 | return "Permission{" + 51 | "name='" + name + '\'' + 52 | ", granted=" + granted + 53 | ", shouldShowRequestPermissionRationale=" + shouldShowRequestPermissionRationale + 54 | '}'; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /app/src/main/java/com/ddc/exoplayertest/permission/PermissionManager.java: -------------------------------------------------------------------------------- 1 | package com.ddc.exoplayertest.permission; 2 | 3 | import android.app.Activity; 4 | import android.os.Build; 5 | 6 | import io.reactivex.functions.Consumer; 7 | 8 | 9 | /** 10 | * @Description: 权限管理 11 | * @author: DAWI 12 | * @date: 2017-04-21 11:21 13 | */ 14 | public class PermissionManager { 15 | 16 | private static PermissionManager permissionManager; 17 | private Activity activity; 18 | 19 | private PermissionManager() { 20 | 21 | } 22 | 23 | public static PermissionManager instance() { 24 | if (permissionManager == null) { 25 | synchronized (PermissionManager.class) { 26 | if (permissionManager == null) { 27 | permissionManager = new PermissionManager(); 28 | } 29 | } 30 | } 31 | return permissionManager; 32 | } 33 | 34 | public PermissionManager with(Activity activity) { 35 | this.activity = activity; 36 | return this; 37 | } 38 | 39 | public void request(final OnPermissionCallback permissionCallback, final String... permissions) { 40 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && this.activity != null && permissionCallback != null) { 41 | RxPermissions rxPermissions = new RxPermissions(this.activity); 42 | rxPermissions.requestEach(permissions).subscribe(new Consumer() { 43 | @Override 44 | public void accept(Permission permission) throws Exception { 45 | if (permission.granted) { 46 | permissionCallback.onRequestAllow(permission.name); 47 | } else if (permission.shouldShowRequestPermissionRationale) { 48 | permissionCallback.onRequestRefuse(permission.name); 49 | } else { 50 | permissionCallback.onRequestNoAsk(permission.name); 51 | } 52 | } 53 | }); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /app/src/main/java/com/ddc/exoplayertest/permission/RxPermissions.java: -------------------------------------------------------------------------------- 1 | package com.ddc.exoplayertest.permission; 2 | 3 | import android.annotation.TargetApi; 4 | import android.app.Activity; 5 | import android.app.FragmentManager; 6 | import android.os.Build; 7 | import android.support.annotation.NonNull; 8 | import android.text.TextUtils; 9 | import android.util.Log; 10 | 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | 14 | import io.reactivex.Observable; 15 | import io.reactivex.ObservableSource; 16 | import io.reactivex.ObservableTransformer; 17 | import io.reactivex.functions.Function; 18 | import io.reactivex.subjects.PublishSubject; 19 | 20 | /** 21 | * @Description: 权限控制 22 | * @author: DAWI 23 | * @date: 2017-04-19 20:14 24 | */ 25 | public class RxPermissions { 26 | 27 | static final String TAG = "RxPermissions"; 28 | 29 | private RxPermissionsFragment mRxPermissionsFragment; 30 | 31 | public RxPermissions(@NonNull Activity activity) { 32 | mRxPermissionsFragment = getRxPermissionsFragment(activity); 33 | } 34 | 35 | private RxPermissionsFragment getRxPermissionsFragment(Activity activity) { 36 | RxPermissionsFragment rxPermissionsFragment = findRxPermissionsFragment(activity); 37 | boolean isNewInstance = rxPermissionsFragment == null; 38 | if (isNewInstance) { 39 | rxPermissionsFragment = new RxPermissionsFragment(); 40 | FragmentManager fragmentManager = activity.getFragmentManager(); 41 | fragmentManager 42 | .beginTransaction() 43 | .add(rxPermissionsFragment, TAG) 44 | .commitAllowingStateLoss(); 45 | fragmentManager.executePendingTransactions(); 46 | } 47 | return rxPermissionsFragment; 48 | } 49 | 50 | private RxPermissionsFragment findRxPermissionsFragment(Activity activity) { 51 | return (RxPermissionsFragment) activity.getFragmentManager().findFragmentByTag(TAG); 52 | } 53 | 54 | /** 55 | * Map emitted items from the source observable into {@code true} if permissions in parameters 56 | * are granted, or {@code false} if not. 57 | *

58 | * If one or several permissions have never been requested, invoke the related framework method 59 | * to ask the user if he allows the permissions. 60 | */ 61 | @SuppressWarnings("WeakerAccess") 62 | public ObservableTransformer ensure(final String... permissions) { 63 | return new ObservableTransformer() { 64 | @Override 65 | public ObservableSource apply(Observable o) { 66 | return request(o, permissions) 67 | // Transform Observable to Observable 68 | .buffer(permissions.length) 69 | .flatMap(new Function, Observable>() { 70 | @Override 71 | public Observable apply(List permissions) throws Exception { 72 | if (permissions.isEmpty()) { 73 | // Occurs during orientation change, when the subject receives onComplete. 74 | // In that case we don't want to propagate that empty list to the 75 | // subscriber, only the onComplete. 76 | return Observable.empty(); 77 | } 78 | // Return true if all permissions are granted. 79 | for (Permission p : permissions) { 80 | if (!p.granted) { 81 | return Observable.just(false); 82 | } 83 | } 84 | return Observable.just(true); 85 | } 86 | }); 87 | } 88 | }; 89 | } 90 | 91 | /** 92 | * Map emitted items from the source observable into {@link Permission} objects for each 93 | * permission in parameters. 94 | *

95 | * If one or several permissions have never been requested, invoke the related framework method 96 | * to ask the user if he allows the permissions. 97 | */ 98 | @SuppressWarnings("WeakerAccess") 99 | public ObservableTransformer ensureEach(final String... permissions) { 100 | return new ObservableTransformer() { 101 | @Override 102 | public ObservableSource apply(Observable o) { 103 | return request(o, permissions); 104 | } 105 | }; 106 | } 107 | 108 | /** 109 | * Request permissions immediately, must be invoked during initialization phase 110 | * of your application. 111 | */ 112 | @SuppressWarnings({"WeakerAccess", "unused"}) 113 | public Observable request(final String... permissions) { 114 | return Observable.just(new Object()).compose(ensure(permissions)); 115 | } 116 | 117 | /** 118 | * Request permissions immediately, must be invoked during initialization phase 119 | * of your application. 120 | */ 121 | @SuppressWarnings({"WeakerAccess", "unused"}) 122 | public Observable requestEach(final String... permissions) { 123 | return Observable.just(new Object()).compose(ensureEach(permissions)); 124 | } 125 | 126 | private Observable request(final Observable trigger, final String... permissions) { 127 | if (permissions == null || permissions.length == 0) { 128 | throw new IllegalArgumentException("RxPermissions.request/requestEach requires at least one input permission"); 129 | } 130 | return oneOf(trigger, pending(permissions)) 131 | .flatMap(new Function>() { 132 | @Override 133 | public Observable apply(Object o) throws Exception { 134 | return requestImplementation(permissions); 135 | } 136 | }); 137 | } 138 | 139 | private Observable pending(final String... permissions) { 140 | for (String p : permissions) { 141 | if (!mRxPermissionsFragment.containsByPermission(p)) { 142 | return Observable.empty(); 143 | } 144 | } 145 | return Observable.just(new Object()); 146 | } 147 | 148 | private Observable oneOf(Observable trigger, Observable pending) { 149 | if (trigger == null) { 150 | return Observable.just(new Object()); 151 | } 152 | return Observable.merge(trigger, pending); 153 | } 154 | 155 | @TargetApi(Build.VERSION_CODES.M) 156 | private Observable requestImplementation(final String... permissions) { 157 | List> list = new ArrayList<>(permissions.length); 158 | List unrequestedPermissions = new ArrayList<>(); 159 | 160 | // In case of multiple permissions, we create an Observable for each of them. 161 | // At the end, the observables are combined to have a unique response. 162 | for (String permission : permissions) { 163 | Log.i("","Requesting permission " + permission); 164 | if (isGranted(permission)) { 165 | // Already granted, or not Android M 166 | // Return a granted Permission object. 167 | list.add(Observable.just(new Permission(permission, true, false))); 168 | continue; 169 | } 170 | 171 | if (isRevoked(permission)) { 172 | // Revoked by a policy, return a denied Permission object. 173 | list.add(Observable.just(new Permission(permission, false, false))); 174 | continue; 175 | } 176 | 177 | PublishSubject subject = mRxPermissionsFragment.getSubjectByPermission(permission); 178 | // Create a new subject if not exists 179 | if (subject == null) { 180 | unrequestedPermissions.add(permission); 181 | subject = PublishSubject.create(); 182 | mRxPermissionsFragment.setSubjectForPermission(permission, subject); 183 | } 184 | 185 | list.add(subject); 186 | } 187 | 188 | if (!unrequestedPermissions.isEmpty()) { 189 | String[] unrequestedPermissionsArray = unrequestedPermissions.toArray(new String[unrequestedPermissions.size()]); 190 | requestPermissionsFromFragment(unrequestedPermissionsArray); 191 | } 192 | return Observable.concat(Observable.fromIterable(list)); 193 | } 194 | 195 | /** 196 | * Invokes Activity.shouldShowRequestPermissionRationale and wraps 197 | * the returned value in an observable. 198 | *

199 | * In case of multiple permissions, only emits true if 200 | * Activity.shouldShowRequestPermissionRationale returned true for 201 | * all revoked permissions. 202 | *

203 | * You shouldn't call this method if all permissions have been granted. 204 | *

205 | * For SDK < 23, the observable will always emit false. 206 | */ 207 | @SuppressWarnings("WeakerAccess") 208 | public Observable shouldShowRequestPermissionRationale(final Activity activity, final String... permissions) { 209 | if (!isMarshmallow()) { 210 | return Observable.just(false); 211 | } 212 | return Observable.just(shouldShowRequestPermissionRationaleImplementation(activity, permissions)); 213 | } 214 | 215 | @TargetApi(Build.VERSION_CODES.M) 216 | private boolean shouldShowRequestPermissionRationaleImplementation(final Activity activity, final String... permissions) { 217 | for (String p : permissions) { 218 | if (!isGranted(p) && !activity.shouldShowRequestPermissionRationale(p)) { 219 | return false; 220 | } 221 | } 222 | return true; 223 | } 224 | 225 | @TargetApi(Build.VERSION_CODES.M) 226 | private void requestPermissionsFromFragment(String[] permissions) { 227 | Log.i("","requestPermissionsFromFragment " + TextUtils.join(", ", permissions)); 228 | mRxPermissionsFragment.requestPermissions(permissions); 229 | } 230 | 231 | /** 232 | * Returns true if the permission is already granted. 233 | *

234 | * Always true if SDK < 23. 235 | */ 236 | @SuppressWarnings("WeakerAccess") 237 | public boolean isGranted(String permission) { 238 | return !isMarshmallow() || mRxPermissionsFragment.isGranted(permission); 239 | } 240 | 241 | /** 242 | * Returns true if the permission has been revoked by a policy. 243 | *

244 | * Always false if SDK < 23. 245 | */ 246 | @SuppressWarnings("WeakerAccess") 247 | public boolean isRevoked(String permission) { 248 | return isMarshmallow() && mRxPermissionsFragment.isRevoked(permission); 249 | } 250 | 251 | private boolean isMarshmallow() { 252 | return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M; 253 | } 254 | 255 | void onRequestPermissionsResult(String permissions[], int[] grantResults) { 256 | mRxPermissionsFragment.onRequestPermissionsResult(permissions, grantResults, new boolean[permissions.length]); 257 | } 258 | } 259 | -------------------------------------------------------------------------------- /app/src/main/java/com/ddc/exoplayertest/permission/RxPermissionsFragment.java: -------------------------------------------------------------------------------- 1 | package com.ddc.exoplayertest.permission; 2 | 3 | 4 | import android.annotation.TargetApi; 5 | import android.app.Fragment; 6 | import android.content.pm.PackageManager; 7 | import android.os.Build; 8 | import android.os.Bundle; 9 | import android.support.annotation.NonNull; 10 | import android.util.Log; 11 | 12 | import java.util.HashMap; 13 | import java.util.Map; 14 | 15 | import io.reactivex.subjects.PublishSubject; 16 | 17 | 18 | /** 19 | * @Description: 申请权限显示 20 | * @author: DAWI 21 | * @date: 2017-04-19 20:20 22 | */ 23 | public class RxPermissionsFragment extends Fragment { 24 | private static final int PERMISSIONS_REQUEST_CODE = 42; 25 | 26 | // Contains all the current permission requests. 27 | // Once granted or denied, they are removed from it. 28 | private Map> mSubjects = new HashMap<>(); 29 | 30 | public RxPermissionsFragment() { 31 | } 32 | 33 | @Override 34 | public void onCreate(Bundle savedInstanceState) { 35 | super.onCreate(savedInstanceState); 36 | setRetainInstance(true); 37 | } 38 | 39 | @TargetApi(Build.VERSION_CODES.M) 40 | void requestPermissions(@NonNull String[] permissions) { 41 | requestPermissions(permissions, PERMISSIONS_REQUEST_CODE); 42 | } 43 | 44 | @TargetApi(Build.VERSION_CODES.M) 45 | public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { 46 | super.onRequestPermissionsResult(requestCode, permissions, grantResults); 47 | 48 | if (requestCode != PERMISSIONS_REQUEST_CODE) return; 49 | 50 | boolean[] shouldShowRequestPermissionRationale = new boolean[permissions.length]; 51 | 52 | for (int i = 0; i < permissions.length; i++) { 53 | shouldShowRequestPermissionRationale[i] = shouldShowRequestPermissionRationale(permissions[i]); 54 | } 55 | 56 | onRequestPermissionsResult(permissions, grantResults, shouldShowRequestPermissionRationale); 57 | } 58 | 59 | void onRequestPermissionsResult(String permissions[], int[] grantResults, boolean[] shouldShowRequestPermissionRationale) { 60 | for (int i = 0, size = permissions.length; i < size; i++) { 61 | Log.i("","onRequestPermissionsResult " + permissions[i]); 62 | // Find the corresponding subject 63 | PublishSubject subject = mSubjects.get(permissions[i]); 64 | if (subject == null) { 65 | // No subject found 66 | Log.e(RxPermissions.TAG, "RxPermissions.onRequestPermissionsResult invoked but didn't find the corresponding permission request."); 67 | return; 68 | } 69 | mSubjects.remove(permissions[i]); 70 | boolean granted = grantResults[i] == PackageManager.PERMISSION_GRANTED; 71 | subject.onNext(new Permission(permissions[i], granted, shouldShowRequestPermissionRationale[i])); 72 | subject.onComplete(); 73 | } 74 | } 75 | 76 | @TargetApi(Build.VERSION_CODES.M) 77 | boolean isGranted(String permission) { 78 | return getActivity().checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED; 79 | } 80 | 81 | @TargetApi(Build.VERSION_CODES.M) 82 | boolean isRevoked(String permission) { 83 | return getActivity().getPackageManager().isPermissionRevokedByPolicy(permission, getActivity().getPackageName()); 84 | } 85 | 86 | public PublishSubject getSubjectByPermission(@NonNull String permission) { 87 | return mSubjects.get(permission); 88 | } 89 | 90 | public boolean containsByPermission(@NonNull String permission) { 91 | return mSubjects.containsKey(permission); 92 | } 93 | 94 | public PublishSubject setSubjectForPermission(@NonNull String permission, @NonNull PublishSubject subject) { 95 | return mSubjects.put(permission, subject); 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /app/src/main/res/anim/dialog_in.xml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /app/src/main/res/anim/dialog_iout.xml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /app/src/main/res/anim/pophidden_anim.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 8 | 9 | 13 | -------------------------------------------------------------------------------- /app/src/main/res/anim/popshow_anim.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | 8 | 12 | -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 12 | 13 | 19 | 22 | 25 | 26 | 27 | 28 | 34 | 35 | -------------------------------------------------------------------------------- /app/src/main/res/drawable-xxhdpi/circle_white.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChangWeiBa/AesExoPlayer/6c1045b6557428c111fcce3c52ce59949941c9a6/app/src/main/res/drawable-xxhdpi/circle_white.png -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 10 | 12 | 14 | 16 | 18 | 20 | 22 | 24 | 26 | 28 | 30 | 32 | 34 | 36 | 38 | 40 | 42 | 44 | 46 | 48 | 50 | 52 | 54 | 56 | 58 | 60 | 62 | 64 | 66 | 68 | 70 | 72 | 74 | 75 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/red_bt_shape.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/video_seekbar.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_test_player.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 11 | 21 | 22 | 30 | 31 | 42 | 43 | 58 | 59 | 69 | 70 | 71 | 72 |