├── .gitignore
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── myth
│ │ └── frameplayer
│ │ └── ExampleInstrumentedTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── myth
│ │ │ └── frameplayer
│ │ │ ├── FramePlayer.java
│ │ │ └── MainActivity.java
│ └── res
│ │ ├── layout
│ │ └── activity_main.xml
│ │ ├── mipmap-hdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-mdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxxhdpi
│ │ └── ic_launcher.png
│ │ ├── values-w820dp
│ │ └── dimens.xml
│ │ └── values
│ │ ├── colors.xml
│ │ ├── dimens.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── com
│ └── myth
│ └── frameplayer
│ └── ExampleUnitTest.java
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── show.gif
/.gitignore:
--------------------------------------------------------------------------------
1 | ### Android ###
2 | # Built application files
3 | *.apk
4 | *.ap_
5 |
6 | # Files for the Dalvik VM
7 | *.dex
8 |
9 | # Java class files
10 | *.class
11 |
12 | # Generated files
13 | bin/
14 | gen/
15 |
16 | # Gradle files
17 | .gradle/
18 | build/
19 |
20 | # Local configuration file (sdk path, etc)
21 | local.properties
22 | signing.properties
23 |
24 | # Proguard folder generated by Eclipse
25 | # proguard/
26 |
27 | # Log Files
28 | *.log
29 |
30 | # Android Studio Navigation editor temp files
31 | .navigation/
32 |
33 | # Android Studio captures folder
34 | captures/
35 |
36 | ### Android Patch ###
37 | gen-external-apklibs
38 |
39 |
40 | ### Intellij ###
41 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
42 |
43 | *.iml
44 |
45 | ## Directory-based project format:
46 | .idea/
47 | # if you remove the above rule, at least ignore the following:
48 |
49 | # User-specific stuff:
50 | # .idea/workspace.xml
51 | # .idea/tasks.xml
52 | # .idea/dictionaries
53 | # .idea/shelf
54 |
55 | # Sensitive or high-churn files:
56 | # .idea/dataSources.ids
57 | # .idea/dataSources.xml
58 | # .idea/sqlDataSources.xml
59 | # .idea/dynamic.xml
60 | # .idea/uiDesigner.xml
61 |
62 | # Gradle:
63 | # .idea/gradle.xml
64 | # .idea/libraries
65 |
66 | # Mongo Explorer plugin:
67 | # .idea/mongoSettings.xml
68 |
69 | ## File-based project format:
70 | *.ipr
71 | *.iws
72 |
73 | ## Plugin-specific files:
74 |
75 | # IntelliJ
76 | /out/
77 |
78 | # mpeltonen/sbt-idea plugin
79 | .idea_modules/
80 |
81 | # JIRA plugin
82 | atlassian-ide-plugin.xml
83 |
84 | # Crashlytics plugin (for Android Studio and IntelliJ)
85 | com_crashlytics_export_strings.xml
86 | crashlytics.properties
87 | crashlytics-build.properties
88 | fabric.properties
89 |
90 | .DS_Store
91 | ### Java ###
92 | *.class
93 |
94 | app/bin/
95 | build
96 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # frameplayer
2 | a video player which can control frame rate base on MediaCodec
3 |
4 | 
5 |
6 | License
7 | =======
8 |
9 | Copyright (c) 2015 myandy
10 |
11 | Licensed under the Apache License, Version 2.0 (the "License");
12 | you may not use this file except in compliance with the License.
13 | You may obtain a copy of the License at
14 |
15 | http://www.apache.org/licenses/LICENSE-2.0
16 |
17 | Unless required by applicable law or agreed to in writing, software
18 | distributed under the License is distributed on an "AS IS" BASIS,
19 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20 | See the License for the specific language governing permissions and
21 | limitations under the License.
22 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 25
5 | buildToolsVersion "25.0.2"
6 | defaultConfig {
7 | applicationId "com.myth.frameplayer"
8 | minSdkVersion 16
9 | targetSdkVersion 25
10 | versionCode 1
11 | versionName "1.0"
12 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | compile fileTree(dir: 'libs', include: ['*.jar'])
24 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
25 | exclude group: 'com.android.support', module: 'support-annotations'
26 | })
27 | compile 'com.android.support:appcompat-v7:25.1.0'
28 | testCompile 'junit:junit:4.12'
29 | }
30 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /home/mi/Android/Sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/myth/frameplayer/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.myth.frameplayer;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumentation test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() throws Exception {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("com.myth.frameplayer", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/app/src/main/java/com/myth/frameplayer/FramePlayer.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2013 Google Inc. All rights reserved.
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 |
17 | package com.myth.frameplayer;
18 |
19 | import android.media.AudioFormat;
20 | import android.media.AudioManager;
21 | import android.media.AudioTrack;
22 | import android.media.MediaCodec;
23 | import android.media.MediaExtractor;
24 | import android.media.MediaFormat;
25 | import android.os.AsyncTask;
26 | import android.os.Build;
27 | import android.os.Handler;
28 | import android.os.Looper;
29 | import android.os.Message;
30 | import android.util.Log;
31 | import android.view.Surface;
32 |
33 | import java.io.File;
34 | import java.io.FileNotFoundException;
35 | import java.io.IOException;
36 | import java.nio.ByteBuffer;
37 | import java.util.Timer;
38 | import java.util.TimerTask;
39 |
40 | import static android.media.MediaExtractor.SEEK_TO_PREVIOUS_SYNC;
41 |
42 |
43 | public class FramePlayer implements Runnable {
44 | private static final String TAG = FramePlayer.class.getSimpleName();
45 |
46 |
47 | private static final int MSG_PLAY_START = 0;
48 |
49 | private static final int MSG_PLAY_PROGRESS = 1;
50 |
51 |
52 | private static final boolean VERBOSE = true;
53 |
54 | private MediaCodec.BufferInfo mBufferInfo = new MediaCodec.BufferInfo();
55 | private ByteBuffer inputBuffer;
56 |
57 | final int TIMEOUT_USEC = 10000;
58 | private AudioTrack audioTrack;
59 |
60 | public void setSourceFile(File sourceFile) {
61 | this.sourceFile = sourceFile;
62 | }
63 |
64 | private File sourceFile;
65 | private Surface mOutputSurface;
66 | private int mVideoWidth;
67 | private int mVideoHeight;
68 |
69 | private MediaExtractor mAudioExtractor;
70 | private MediaExtractor mMediaExtractor;
71 | private MediaCodec mAudioCodec;
72 | private MediaCodec mMediaCodec;
73 | private int mTrackIndex;
74 | private int mAudioTrackIndex;
75 | private Thread mThread;
76 | private LocalHandler mLocalHandler;
77 |
78 | public void setPlayListener(PlayListener playListener) {
79 | this.playListener = playListener;
80 | }
81 |
82 | private PlayListener playListener;
83 |
84 | public void setFrameInterval(int frameRate) {
85 | if (frameRate < 1 || frameRate > 100) {
86 | throw new IllegalArgumentException("frame rate must between 1 to 100");
87 | }
88 | this.mFrameInterval = 1000 / frameRate;
89 | }
90 |
91 | private int mFrameInterval;
92 | private int videoFrameRate;
93 |
94 |
95 | public FramePlayer(Surface outputSurface) {
96 | mOutputSurface = outputSurface;
97 | }
98 |
99 | private int frame;
100 | private Timer timer;
101 | private TimerTask timerTask;
102 |
103 | private long duration;
104 | private boolean seekOffsetFlag = false;
105 | private boolean isLoop = false;
106 | private boolean hadPlay = false;
107 | private int seekOffset = 0;
108 | private boolean doStop = false;
109 | private AudioPlayTask mAudioPlayTask;
110 |
111 | private volatile boolean isRunning;
112 |
113 | public void nextFrame() {
114 | mLocalHandler.sendMessage(mLocalHandler.obtainMessage(MSG_PLAY_PROGRESS, frame++, 0));
115 | }
116 |
117 | private class ProgressTimerTask extends java.util.TimerTask {
118 | @Override
119 | public void run() {
120 | if (isRunning) {
121 | mLocalHandler.sendMessage(mLocalHandler.obtainMessage(MSG_PLAY_PROGRESS, frame++, 0));
122 | }
123 | }
124 | }
125 |
126 |
127 | @Override
128 | public void run() {
129 | // Establish a Looper for this thread, and define a Handler for it.
130 | Looper.prepare();
131 | mLocalHandler = new LocalHandler();
132 | Looper.loop();
133 | }
134 |
135 | private class LocalHandler extends Handler {
136 | @Override
137 | public void handleMessage(Message msg) {
138 | int what = msg.what;
139 | Log.d(TAG, "handleMessage:" + what);
140 | switch (what) {
141 | case MSG_PLAY_START:
142 | try {
143 | play();
144 | } catch (IOException e) {
145 | e.printStackTrace();
146 | }
147 | break;
148 | case MSG_PLAY_PROGRESS:
149 | doExtract(msg.arg1);
150 | break;
151 | default:
152 | throw new RuntimeException("Unknown msg " + what);
153 | }
154 | }
155 | }
156 |
157 |
158 | /**
159 | * Creates a new thread, and starts execution of the player.
160 | */
161 | public void execute() {
162 | mThread = new Thread(this, "Movie Player");
163 | mThread.start();
164 | }
165 |
166 |
167 | public void start() {
168 | stop();
169 | frame = 0;
170 | isRunning = true;
171 | mLocalHandler.sendEmptyMessage(MSG_PLAY_START);
172 | }
173 |
174 | public void stop() {
175 | if (timer != null) {
176 | timer.cancel();
177 | timerTask.cancel();
178 | timer = null;
179 | timerTask = null;
180 | isRunning = false;
181 | }
182 | if (mAudioPlayTask != null) {
183 | mAudioPlayTask.cancel(true);
184 | }
185 | doStop = true;
186 | seekOffset = 0;
187 | seekOffsetFlag = false;
188 | }
189 |
190 |
191 | public boolean isRunning() {
192 | return isRunning;
193 | }
194 |
195 |
196 | public void pause() {
197 | if (isRunning) {
198 | isRunning = false;
199 | }
200 | }
201 |
202 | public void resume() {
203 | if (!isRunning) {
204 | isRunning = true;
205 | }
206 | }
207 |
208 |
209 | /**
210 | * Returns the width, in pixels, of the video.
211 | */
212 | public int getVideoWidth() {
213 | return mVideoWidth;
214 | }
215 |
216 | /**
217 | * Returns the height, in pixels, of the video.
218 | */
219 | public int getVideoHeight() {
220 | return mVideoHeight;
221 | }
222 |
223 |
224 | private void play() throws IOException {
225 | if (!sourceFile.canRead()) {
226 | throw new FileNotFoundException("Unable to read " + sourceFile);
227 | }
228 | try {
229 | destroyExtractor();
230 | mMediaExtractor = new MediaExtractor();
231 | mMediaExtractor.setDataSource(sourceFile.toString());
232 | mTrackIndex = selectTrack(mMediaExtractor);
233 | if (mTrackIndex < 0) {
234 | throw new RuntimeException("No video track found in " + sourceFile);
235 | }
236 | MediaFormat format = mMediaExtractor.getTrackFormat(mTrackIndex);
237 | videoFrameRate = format.getInteger(MediaFormat.KEY_FRAME_RATE);
238 | if (mFrameInterval == 0) {
239 | mFrameInterval = 1000 / videoFrameRate;
240 | }
241 | String mime = format.getString(MediaFormat.KEY_MIME);
242 | duration = format.getLong(MediaFormat.KEY_DURATION);
243 |
244 |
245 | mAudioExtractor = new MediaExtractor();
246 | mAudioExtractor.setDataSource(sourceFile.toString());
247 | mAudioTrackIndex = selectAudioTrack(mAudioExtractor);
248 |
249 | //only support pcm
250 | if (mAudioTrackIndex != -1) {
251 | relaxResources(true);
252 | MediaFormat audioFormat = mMediaExtractor.getTrackFormat(mAudioTrackIndex);
253 | String audioMime = audioFormat.getString(MediaFormat.KEY_MIME);
254 | try {
255 | // 实例化一个指定类型的解码器,提供数据输出
256 | mAudioCodec = MediaCodec.createDecoderByType(audioMime);
257 | } catch (IOException e) {
258 | e.printStackTrace();
259 | }
260 |
261 | mAudioCodec.configure(audioFormat, null /* surface */, null /* crypto */, 0 /* flags */);
262 | mAudioCodec.start();
263 |
264 |
265 | int channels = audioFormat.getInteger(MediaFormat.KEY_CHANNEL_COUNT);
266 | int sampleRate = (int) (1.0f * audioFormat.getInteger(MediaFormat.KEY_SAMPLE_RATE) * (1000 / videoFrameRate) / mFrameInterval);
267 | int channelConfiguration = channels == 1 ? AudioFormat.CHANNEL_OUT_MONO : AudioFormat.CHANNEL_OUT_STEREO;
268 | audioTrack = new AudioTrack(
269 | AudioManager.STREAM_MUSIC,
270 | sampleRate,
271 | channelConfiguration,
272 | AudioFormat.ENCODING_PCM_16BIT,
273 | AudioTrack.getMinBufferSize(
274 | sampleRate,
275 | channelConfiguration,
276 | AudioFormat.ENCODING_PCM_16BIT
277 | ),
278 | AudioTrack.MODE_STREAM
279 | );
280 |
281 | //开始play,等待write发出声音
282 | audioTrack.play();
283 | mAudioExtractor.selectTrack(mAudioTrackIndex);
284 | }
285 |
286 |
287 | mMediaExtractor.selectTrack(mTrackIndex);
288 | mMediaCodec = MediaCodec.createDecoderByType(mime);
289 | mMediaCodec.configure(format, mOutputSurface, null, 0);
290 | mMediaCodec.start();
291 |
292 | timer = new Timer();
293 | timerTask = new ProgressTimerTask();
294 | timer.schedule(timerTask, 0, mFrameInterval);
295 |
296 | mAudioPlayTask = new AudioPlayTask();
297 | mAudioPlayTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
298 |
299 | } catch (Exception e) {
300 | Log.e(TAG, e.toString());
301 | destroyExtractor();
302 | }
303 | }
304 |
305 |
306 | private void destroyExtractor() {
307 | if (mMediaCodec != null) {
308 | mMediaCodec.stop();
309 | mMediaCodec.release();
310 | mMediaCodec = null;
311 | }
312 | if (mMediaExtractor != null) {
313 | mMediaExtractor.release();
314 | mMediaExtractor = null;
315 | }
316 | }
317 |
318 | private void relaxResources(Boolean release) {
319 | if (mAudioCodec != null) {
320 | if (release) {
321 | mAudioCodec.stop();
322 | mAudioCodec.release();
323 | mAudioCodec = null;
324 | }
325 |
326 | }
327 | if (audioTrack != null) {
328 | if (!doStop)
329 | audioTrack.flush();
330 | audioTrack.release();
331 | audioTrack = null;
332 | }
333 | }
334 |
335 |
336 | /**
337 | * Selects the video track, if any.
338 | *
339 | * @return the track index, or -1 if no video track is found.
340 | */
341 | private static int selectTrack(MediaExtractor mMediaExtractor) {
342 | // Select the first video track we find, ignore the rest.
343 | int numTracks = mMediaExtractor.getTrackCount();
344 | for (int i = 0; i < numTracks; i++) {
345 | MediaFormat format = mMediaExtractor.getTrackFormat(i);
346 | String mime = format.getString(MediaFormat.KEY_MIME);
347 | if (mime.startsWith("video/")) {
348 | if (VERBOSE) {
349 | Log.d(TAG, "Extractor selected track " + i + " (" + mime + "): " + format);
350 | }
351 | return i;
352 | }
353 | }
354 |
355 | return -1;
356 | }
357 |
358 | private int selectAudioTrack(MediaExtractor mMediaExtractor) {
359 | for (int i = 0; i < mMediaExtractor.getTrackCount(); i++) {
360 | MediaFormat format = mMediaExtractor.getTrackFormat(i);
361 | if (format.getString(MediaFormat.KEY_MIME).startsWith("audio/")) {
362 | return i;
363 | }
364 | }
365 | return -1;
366 | }
367 |
368 | private long curPosition;
369 |
370 | private void doAudio() {
371 |
372 | ByteBuffer[] codecInputBuffers;
373 | ByteBuffer[] codecOutputBuffers;
374 |
375 |
376 | MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
377 |
378 | codecInputBuffers = mAudioCodec.getInputBuffers();
379 | // 解码后的数据
380 | codecOutputBuffers = mAudioCodec.getOutputBuffers();
381 |
382 | // 解码
383 | boolean sawInputEOS = false;
384 | boolean sawOutputEOS = false;
385 | int noOutputCounter = 0;
386 | int noOutputCounterLimit = 50;
387 |
388 | int inputBufIndex;
389 | doStop = false;
390 | while (!sawOutputEOS && noOutputCounter < noOutputCounterLimit && !doStop) {
391 |
392 | if (!isRunning) {
393 | try {
394 | //防止死循环ANR
395 | Thread.sleep(500);
396 | } catch (InterruptedException e) {
397 | e.printStackTrace();
398 | }
399 | continue;
400 | }
401 |
402 | noOutputCounter++;
403 | if (!sawInputEOS) {
404 | if (seekOffsetFlag) {
405 | seekOffsetFlag = false;
406 | mAudioExtractor.seekTo(seekOffset, SEEK_TO_PREVIOUS_SYNC);
407 | }
408 |
409 | inputBufIndex = mAudioCodec.dequeueInputBuffer(TIMEOUT_USEC);
410 |
411 | if (inputBufIndex >= 0) {
412 | ByteBuffer dstBuf = codecInputBuffers[inputBufIndex];
413 |
414 | int sampleSize =
415 | mAudioExtractor.readSampleData(dstBuf, 0 /* offset */);
416 |
417 | long presentationTimeUs = 0;
418 |
419 | if (sampleSize < 0) {
420 | sawInputEOS = true;
421 | sampleSize = 0;
422 | } else {
423 | presentationTimeUs = mAudioExtractor.getSampleTime();
424 | }
425 | curPosition = presentationTimeUs;
426 | mAudioCodec.queueInputBuffer(
427 | inputBufIndex,
428 | 0 /* offset */,
429 | sampleSize,
430 | presentationTimeUs,
431 | sawInputEOS ? MediaCodec.BUFFER_FLAG_END_OF_STREAM : 0);
432 |
433 |
434 | if (!sawInputEOS) {
435 | mAudioExtractor.advance();
436 | }
437 | } else {
438 | Log.e(TAG, "inputBufIndex " + inputBufIndex);
439 | }
440 | }
441 |
442 | // decode to PCM and push it to the AudioTrack player
443 | // 解码数据为PCM
444 | int res = mAudioCodec.dequeueOutputBuffer(info, TIMEOUT_USEC);
445 |
446 | if (res >= 0) {
447 | if (info.size > 0) {
448 | noOutputCounter = 0;
449 | }
450 | int outputBufIndex = res;
451 | ByteBuffer buf = codecOutputBuffers[outputBufIndex];
452 |
453 | final byte[] chunk = new byte[info.size];
454 | buf.get(chunk);
455 | buf.clear();
456 | if (chunk.length > 0 && audioTrack != null && !doStop) {
457 | //播放
458 | audioTrack.write(chunk, 0, chunk.length);
459 | hadPlay = true;
460 | }
461 | //释放
462 | mAudioCodec.releaseOutputBuffer(outputBufIndex, false /* render */);
463 | if ((info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
464 | sawOutputEOS = true;
465 | }
466 | } else if (res == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
467 | codecOutputBuffers = mAudioCodec.getOutputBuffers();
468 | } else if (res == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
469 | MediaFormat oformat = mAudioCodec.getOutputFormat();
470 | } else {
471 | }
472 | }
473 |
474 | relaxResources(true);
475 |
476 | doStop = true;
477 |
478 | if (sawOutputEOS) {
479 | try {
480 | if (isLoop || !hadPlay) {
481 | doAudio();
482 | return;
483 | }
484 | } catch (Exception e) {
485 | e.printStackTrace();
486 | }
487 | }
488 | }
489 |
490 |
491 | /**
492 | * AsyncTask that takes care of running the decode/playback loop
493 | */
494 | private class AudioPlayTask extends AsyncTask {
495 |
496 | @Override
497 | protected Void doInBackground(Void... values) {
498 | doAudio();
499 | return null;
500 | }
501 |
502 | @Override
503 | protected void onPreExecute() {
504 | }
505 |
506 | @Override
507 | protected void onProgressUpdate(Void... values) {
508 | }
509 | }
510 |
511 |
512 | private void doExtract(int frame) {
513 |
514 | if (mMediaCodec == null) {
515 | return;
516 | }
517 | int inputBufferIndex = 0;
518 | try {
519 | inputBufferIndex = mMediaCodec.dequeueInputBuffer(TIMEOUT_USEC);
520 | } catch (Exception e) {
521 | // TODO: 17-3-21 error after onResume,in none exxcuting state
522 | return;
523 | }
524 | if (inputBufferIndex >= 0) {
525 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
526 | // 从输入队列里去空闲outputBufferfer
527 | inputBuffer = mMediaCodec.getInputBuffers()[inputBufferIndex];
528 | } else {
529 | // SDK_INT > LOLLIPOP
530 | inputBuffer = mMediaCodec.getInputBuffer(inputBufferIndex);
531 | }
532 | if (null != inputBuffer) {
533 | int chunkSize = mMediaExtractor.readSampleData(inputBuffer, 0);
534 | if (chunkSize < 0) {
535 | if (isRunning && playListener != null) {
536 | playListener.onCompleted();
537 | isRunning = false;
538 | destroyExtractor();
539 | return;
540 | }
541 | mMediaCodec.queueInputBuffer(inputBufferIndex, 0, 0, 0L,
542 | MediaCodec.BUFFER_FLAG_END_OF_STREAM);
543 | if (VERBOSE) Log.d(TAG, "sent input EOS");
544 | } else {
545 | mMediaCodec.queueInputBuffer(inputBufferIndex, 0, chunkSize, 0, 0);
546 | mMediaExtractor.advance();
547 | }
548 | }
549 |
550 | int outputBufferIndex = mMediaCodec.dequeueOutputBuffer(mBufferInfo, TIMEOUT_USEC);
551 | Log.d(TAG, outputBufferIndex + ":outputBufferIndex");
552 | if (outputBufferIndex >= 0) {
553 | mMediaCodec.releaseOutputBuffer(outputBufferIndex, true);
554 | if (playListener != null) {
555 | playListener.onProgress((frame + 1) * mFrameInterval * 1f / duration);
556 | }
557 | } else {
558 | Log.d(TAG, "Reached EOS, looping");
559 | }
560 | }
561 | }
562 |
563 | public interface PlayListener {
564 |
565 | void onCompleted();
566 |
567 | void onProgress(float progress);
568 | }
569 |
570 |
571 | }
572 |
--------------------------------------------------------------------------------
/app/src/main/java/com/myth/frameplayer/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.myth.frameplayer;
2 |
3 | import android.os.Bundle;
4 | import android.os.Environment;
5 | import android.support.v7.app.AppCompatActivity;
6 | import android.util.DisplayMetrics;
7 | import android.util.Log;
8 | import android.view.Surface;
9 | import android.view.SurfaceHolder;
10 | import android.view.SurfaceView;
11 | import android.view.View;
12 | import android.widget.EditText;
13 | import android.widget.RelativeLayout;
14 | import android.widget.TextView;
15 | import android.widget.Toast;
16 |
17 | import java.io.File;
18 |
19 |
20 | /**
21 | * warn:
22 | * need get file read permission first
23 | */
24 | public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback {
25 |
26 | /**
27 | * test video path
28 | */
29 | private static String videoPath = Environment.getExternalStorageDirectory().getPath() + "/Music8.1.mp4";
30 | private FramePlayer framePlayer = null;
31 |
32 |
33 | @Override
34 | protected void onCreate(Bundle savedInstanceState) {
35 | super.onCreate(savedInstanceState);
36 | setContentView(R.layout.activity_main);
37 | SurfaceView surfaceView = (SurfaceView) findViewById(R.id.playMovie_surface);
38 | surfaceView.getHolder().addCallback(this);
39 |
40 | //make its height same with width,should set for video size
41 | DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
42 | RelativeLayout.LayoutParams lps = (RelativeLayout.LayoutParams) surfaceView.getLayoutParams();
43 | lps.width = (int) (displayMetrics.widthPixels - 2 * getResources().getDimension(R.dimen.activity_horizontal_margin));
44 | lps.height = lps.width;
45 | surfaceView.setLayoutParams(lps);
46 |
47 | final EditText et = (EditText) findViewById(R.id.et);
48 |
49 | findViewById(R.id.play).setOnClickListener(new View.OnClickListener() {
50 | @Override
51 | public void onClick(View v) {
52 | if (et.getText().toString().isEmpty()) {
53 | framePlayer.start();
54 | } else {
55 | int frame = Integer.parseInt(et.getText().toString());
56 | if (frame >= 1 && frame <= 100) {
57 | framePlayer.setFrameInterval(frame);
58 | framePlayer.start();
59 | } else {
60 | Toast.makeText(MainActivity.this, "每秒帧数必须在1到100之间!", Toast.LENGTH_SHORT).show();
61 | }
62 | }
63 | }
64 | });
65 |
66 | final TextView tv = (TextView) findViewById(R.id.control);
67 | findViewById(R.id.control).setOnClickListener(new View.OnClickListener() {
68 | @Override
69 | public void onClick(View v) {
70 | if (framePlayer.isRunning()) {
71 | framePlayer.pause();
72 | tv.setText("RESUME");
73 | } else {
74 | tv.setText("PAUSE");
75 | framePlayer.resume();
76 | }
77 | }
78 | });
79 |
80 | findViewById(R.id.next).setOnClickListener(new View.OnClickListener() {
81 | @Override
82 | public void onClick(View v) {
83 | framePlayer.nextFrame();
84 | }
85 | });
86 | }
87 |
88 | @Override
89 | protected void onPause() {
90 | super.onPause();
91 | if (framePlayer != null) {
92 | framePlayer.pause();
93 | }
94 |
95 | }
96 |
97 | @Override
98 | public void surfaceCreated(SurfaceHolder holder) {
99 | if (framePlayer == null) {
100 | Surface surface = holder.getSurface();
101 | framePlayer = new FramePlayer(surface);
102 | framePlayer.setSourceFile(new File(videoPath));
103 | framePlayer.execute();
104 | framePlayer.setPlayListener(new FramePlayer.PlayListener() {
105 | @Override
106 | public void onCompleted() {
107 | Log.d("PlayListener", "onCompleted");
108 | }
109 |
110 | @Override
111 | public void onProgress(float progress) {
112 | Log.d("PlayListener", "onProgress" + progress);
113 | }
114 | });
115 | }
116 | }
117 |
118 | @Override
119 | public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
120 |
121 | }
122 |
123 | @Override
124 | public void surfaceDestroyed(SurfaceHolder holder) {
125 |
126 | }
127 | }
128 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
13 |
14 |
20 |
21 |
28 |
29 |
39 |
40 |
50 |
51 |
61 |
62 |
63 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/myandy/frameplayer/2f245a59678391c06ae2f43270c86a7a4a50548e/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/myandy/frameplayer/2f245a59678391c06ae2f43270c86a7a4a50548e/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/myandy/frameplayer/2f245a59678391c06ae2f43270c86a7a4a50548e/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/myandy/frameplayer/2f245a59678391c06ae2f43270c86a7a4a50548e/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/myandy/frameplayer/2f245a59678391c06ae2f43270c86a7a4a50548e/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | FramePlayer
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/test/java/com/myth/frameplayer/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.myth.frameplayer;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() throws Exception {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | jcenter()
6 | }
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:2.2.2'
9 |
10 | // NOTE: Do not place your application dependencies here; they belong
11 | // in the individual module build.gradle files
12 | }
13 | }
14 |
15 | allprojects {
16 | repositories {
17 | jcenter()
18 | }
19 | }
20 |
21 | task clean(type: Delete) {
22 | delete rootProject.buildDir
23 | }
24 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | org.gradle.jvmargs=-Xmx1536m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/myandy/frameplayer/2f245a59678391c06ae2f43270c86a7a4a50548e/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Dec 28 10:00:20 PST 2015
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------
/show.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/myandy/frameplayer/2f245a59678391c06ae2f43270c86a7a4a50548e/show.gif
--------------------------------------------------------------------------------