├── .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 | 
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 | 
46 |
47 | 而我们需要实现的需求中,本质上只是把MP3文件加密了一次而已,它在播放的时候,最终只需要在拆解提供资源的时候把加密的文件流解密成正常的MP3流,给ExtractorMediaSource提供正常的MP3流即可,所以并不需要再过多的进行其他复杂操作就可以完成此需求。
48 |
49 | 那么我实现的就是重写DefaultDataSourceFactory资源提供工厂类,改造DefaultDataSource,根据文件类型判断,加密的音频使用Aes128DataSource类拆解进行解密,未加密或者在线的URL继续使用getFileDataSource或者getContentDataSource原本默认的实现进行拆解。最后只需要用我们改写的factory替换默认的DataSourceFactory就可以完成我们的需求了。
50 |
51 | 
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 |
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 super DataSource> 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 super DataSource> 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 super DataSource> 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 super DataSource> 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 super DataSource> 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 super DataSource> 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 super DataSource> 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
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