├── .gitignore ├── .idea ├── compiler.xml ├── copyright │ └── profiles_settings.xml ├── encodings.xml ├── gradle.xml ├── inspectionProfiles │ ├── Project_Default.xml │ └── profiles_settings.xml ├── misc.xml ├── modules.xml └── runConfigurations.xml ├── LICENSE ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── example │ │ └── administrator │ │ └── videorecorddemo │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── administrator │ │ │ └── videorecorddemo │ │ │ ├── MainActivity.java │ │ │ ├── OrientationSensorListener.java │ │ │ ├── VedioRecordActivity.java │ │ │ ├── VideoPlayActivity.java │ │ │ ├── VideoProgressView.java │ │ │ └── VideoRecordSurface.java │ └── res │ │ ├── drawable │ │ ├── libvideo_recorder_default.xml │ │ ├── title_left_arrow_white.png │ │ └── title_more_white.png │ │ ├── layout │ │ ├── activity_main.xml │ │ ├── activity_vedio_record.xml │ │ └── activity_video_play.xml │ │ ├── mipmap-hdpi │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxxhdpi │ │ └── ic_launcher.png │ │ ├── values-w820dp │ │ └── dimens.xml │ │ └── values │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── example │ └── administrator │ └── videorecorddemo │ └── ExampleUnitTest.java ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── img ├── GIF2.gif ├── a.jpg ├── b.jpg ├── c.jpg ├── d.png ├── e.png └── f.png └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/workspace.xml 5 | /.idea/libraries 6 | .DS_Store 7 | /build 8 | /captures 9 | .externalNativeBuild 10 | -------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /.idea/copyright/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 17 | 18 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 10 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 19 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 46 | 47 | 48 | 49 | 50 | 1.8 51 | 52 | 57 | 58 | 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | -------------------------------------------------------------------------------- /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. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | [博客地址文章地址](http://blog.csdn.net/sw5131899/article/details/74390640) 3 | 4 | ![image](https://github.com/SingleShu/VideoRecord/raw/master/img/GIF2.gif) 5 | 6 | 制作的gif图有噪点没办法啊。还是看看截图吧 7 | 8 | 9 | ![image](https://github.com/SingleShu/VideoRecord/raw/master/img/a.jpg) 10 | 11 | 12 | ![image](https://github.com/SingleShu/VideoRecord/raw/master/img/b.jpg) 13 | 14 | ![image](https://github.com/SingleShu/VideoRecord/raw/master/img/c.jpg) 15 | 16 | 好吧,都是恍恍惚惚红红火火~。不过这些都是小事儿,我最后会把代码放在git上,需要的朋友自己去拉下来跑一下就知道效果了。 17 | 18 | ![image](https://github.com/SingleShu/VideoRecord/raw/master/img/d.png) 19 | 20 | 一共就是这些类。当然最重要还是VideoRecordSurface这个类里面的逻辑,对摄像头做了各种初始化,设置还有录制的视频质量,时间等相关设置。 21 | 22 | ![image](https://github.com/SingleShu/VideoRecord/raw/master/img/e.png) 23 | 24 | 视频存放的默认地址,在外面设置,这样不用每次都去修改里面的代码嘛。相关的最小录制时间,最大录制时间,我们老板说了,微信只能录6秒,那咱们也要录6秒。时间短了就算没录上。好吧,加了两个限制参数就ok了。当然还要能手动取消录制啊。这个需要在onTouch的事件中做处理了。当然还要录制视频的第一帧做显示,还要有个进度条,为了让用户知道自己录制了多少嘛。好吧,这些都easy。 25 | 问题一个一个来解决: 26 | 27 | 28 | 1、如何拿到视频第一帧? 29 | 30 | 31 | ![image](https://github.com/SingleShu/VideoRecord/raw/master/img/f.png) 32 | 33 | 谷歌提供的媒体相关api中有个 MediaMetadataRetriever,设置资源来源之后。可以获取该资源相关的信息。ok了。 34 | 35 | 36 | 2、如何展示进度条,自定义进度条。 37 | 38 | 39 | 自定义一个不就Ok了,一条线,主要的还是如何更新,把更新相关设置暴露给调用层。需要几秒,就设置几秒,开启一个线程,然后每一秒回调更新UI就搞定了,这里要调用postInvalidate(); 40 | ``` 41 | public class VideoProgressView extends View { 42 | private Paint mProgressPaint;//进度条的画笔 43 | private int mProgress = 0;//进度条 44 | private int mHeight; 45 | private int mWidth; 46 | private Handler mHandler; 47 | 48 | public VideoProgressView(Context context) { 49 | this(context, null); 50 | } 51 | 52 | public VideoProgressView(Context context, AttributeSet attrs) { 53 | this(context, attrs, -1); 54 | } 55 | 56 | public VideoProgressView(Context context, AttributeSet attrs, int defStyleAttr) { 57 | super(context, attrs, defStyleAttr); 58 | setBackgroundColor(Color.TRANSPARENT); 59 | mHandler = new Handler(Looper.getMainLooper()); 60 | } 61 | 62 | 63 | private Paint getDefaultPaint() { 64 | if (mProgressPaint == null) { 65 | mProgressPaint = new Paint(); 66 | mProgressPaint.setAntiAlias(true); 67 | mProgressPaint.setColor(Color.GREEN); 68 | mProgressPaint.setStyle(Paint.Style.FILL_AND_STROKE); 69 | mProgressPaint.setStrokeWidth(mHeight * 2); 70 | } 71 | return mProgressPaint; 72 | } 73 | 74 | @Override 75 | protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 76 | mWidth = measureWidth(widthMeasureSpec); 77 | mHeight = measureHeight(heightMeasureSpec); 78 | setMeasuredDimension(widthMeasureSpec, heightMeasureSpec); 79 | } 80 | 81 | private int measureWidth(int widthMeasureSpec) { 82 | int width; 83 | int widthMode = MeasureSpec.getMode(widthMeasureSpec); 84 | int widthSize = MeasureSpec.getSize(widthMeasureSpec); 85 | if (widthMode == MeasureSpec.EXACTLY) { 86 | // Parent has told us how big to be. So be it. 87 | width = widthSize; 88 | } else { 89 | width = 200; 90 | if (widthMode == MeasureSpec.AT_MOST) { 91 | width = Math.min(width, widthSize); 92 | } 93 | } 94 | return width; 95 | } 96 | 97 | private int measureHeight(int heightMeasureSpec) { 98 | int height; 99 | int heightMode = MeasureSpec.getMode(heightMeasureSpec); 100 | int heightSize = MeasureSpec.getSize(heightMeasureSpec); 101 | if (heightMode == MeasureSpec.EXACTLY) { 102 | // Parent has told us how big to be. So be it. 103 | height = heightSize; 104 | } else { 105 | height = 50; 106 | if (heightMode == MeasureSpec.AT_MOST) { 107 | height = Math.min(heightMeasureSpec, height); 108 | } 109 | } 110 | return height; 111 | } 112 | 113 | @Override 114 | protected void onDraw(Canvas canvas) { 115 | super.onDraw(canvas); 116 | float startX = mProgress; 117 | float startY = mHeight; 118 | float stopX = mWidth - mProgress; 119 | float stopY = mHeight; 120 | canvas.drawLine(startX, startY, stopX, stopY, getDefaultPaint()); 121 | } 122 | 123 | /** 124 | * 设置进度条 125 | * 126 | * @param second 秒 127 | */ 128 | public void startProgress(final int second) { 129 | isProgress = true; 130 | setVisibility(VISIBLE); 131 | new Thread(new Runnable() { 132 | @Override 133 | public void run() { 134 | int count = mWidth / 2; 135 | int sleepTime = second * 1000 / count; 136 | for (int i = 0; i < count; i++) { 137 | 138 | if ((i == count - 1) || !isProgress) { 139 | mHandler.post(new Runnable() { 140 | @Override 141 | public void run() { 142 | setVisibility(INVISIBLE); 143 | } 144 | }); 145 | break; 146 | } else { 147 | mProgress = i; 148 | postInvalidate(); 149 | SystemClock.sleep(sleepTime); 150 | } 151 | 152 | 153 | } 154 | } 155 | }).start(); 156 | } 157 | 158 | private boolean isProgress; 159 | 160 | public void stopProgress() { 161 | isProgress = false; 162 | } 163 | 164 | } 165 | ``` 166 | 167 | 168 | 3、如何实现手动取消呢? 169 | 170 | 171 | 这个需要在录制的Activity里做文章了,自定义的Surface保证功能单一,只是摄像头视频录制相关设置。我们首先要分析点击录制那个按钮有几个状态。第一,点下去,是开始录制视频。第二,一直按着,滑动到按钮范围外取消。第三、抬起。抬起时需要判断抬起位置和按住的时间长短是否达到了最短时间。这就是onTouch的三个状态。那么就设置button的onTouch了。 172 | 173 | ``` 174 | btnStart.setOnTouchListener(new View.OnTouchListener() { 175 | private float moveY; 176 | private float moveX; 177 | Rect rect = new Rect(); 178 | boolean isInner = true; 179 | 180 | @Override 181 | public boolean onTouch(View v, MotionEvent event) { 182 | switch (event.getAction()) { 183 | case MotionEvent.ACTION_DOWN: { 184 | //按住事件发生后执行代码的区域 185 | tvTips.setVisibility(View.VISIBLE); 186 | videoRecordSurface.record(VedioRecordActivity.this,listener.getOrientationHintDegrees()); 187 | videoProgressView.startProgress(videoRecordSurface.mRecordMaxTime); 188 | break; 189 | } 190 | case MotionEvent.ACTION_MOVE: { 191 | //移动事件发生后执行代码的区域 192 | if (rect.right == 0 && rect.bottom == 0) { 193 | btnStart.getFocusedRect(rect); 194 | } 195 | moveX = event.getX(); 196 | moveY = event.getY(); 197 | if (moveY > 0 && moveX > 0 && moveX <= rect.right && moveY <= rect.bottom) { 198 | //内 199 | isInner = true; 200 | if (!"移开取消".equals(tvTips.getText().toString().trim())) { 201 | tvTips.setBackgroundColor(Color.TRANSPARENT); 202 | tvTips.setTextColor(getResources().getColor(R.color.video_green)); 203 | tvTips.setText("移开取消"); 204 | } 205 | btnStart.setVisibility(View.INVISIBLE); 206 | } else { 207 | //外 208 | isInner = false; 209 | if (!"松开取消".equals(tvTips.getText().toString().trim())) { 210 | tvTips.setBackgroundColor(Color.RED);//getResources().getColor(android.R.color.holo_red_dark)); 211 | tvTips.setTextColor(Color.WHITE); 212 | tvTips.setText("松开取消"); 213 | } 214 | } 215 | break; 216 | } 217 | case MotionEvent.ACTION_UP: { 218 | //松开事件发生后执行代码的区域 219 | tvTips.setVisibility(View.INVISIBLE); 220 | videoProgressView.stopProgress(); 221 | if (iTime <= videoRecordSurface.mRecordMiniTime || (iTime < videoRecordSurface.mRecordMaxTime && !isInner)) { 222 | if (isInner) { 223 | Toast.makeText(VedioRecordActivity.this, "录制时间太短", Toast.LENGTH_SHORT).show(); 224 | } else { 225 | // 226 | } 227 | videoRecordSurface.stopRecord(); 228 | videoRecordSurface.repCamera(); 229 | btnStart.setVisibility(View.VISIBLE); 230 | } else if(iTime < videoRecordSurface.mRecordMaxTime){ 231 | videoRecordSurface.stop(); 232 | } 233 | break; 234 | } 235 | default: 236 | break; 237 | } 238 | return false; 239 | } 240 | }); 241 | ``` 242 | 好啦。录制,保存,取消,时间长短,进度条都解决了。代码就不都贴出来了,上传到git上吧,有需要的自己拉下来瞅瞅。亲测有效。觉得有用给个star,谢谢了 。 -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 25 5 | buildToolsVersion "25.0.3" 6 | defaultConfig { 7 | applicationId "com.example.administrator.videorecorddemo" 8 | minSdkVersion 19 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.3.1' 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 D:\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/example/administrator/videorecorddemo/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.example.administrator.videorecorddemo; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Instrumentation test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() throws Exception { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("com.example.administrator.videorecorddemo", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 26 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /app/src/main/java/com/example/administrator/videorecorddemo/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.example.administrator.videorecorddemo; 2 | 3 | import android.content.Intent; 4 | import android.os.Environment; 5 | import android.support.v7.app.AppCompatActivity; 6 | import android.os.Bundle; 7 | import android.view.View; 8 | import android.widget.Button; 9 | 10 | public class MainActivity extends AppCompatActivity { 11 | 12 | Button button; 13 | String videoPath; 14 | 15 | @Override 16 | protected void onCreate(Bundle savedInstanceState) { 17 | super.onCreate(savedInstanceState); 18 | setContentView(R.layout.activity_main); 19 | button = (Button) findViewById(R.id.btn_record_video); 20 | videoPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/customVideo/"; 21 | button.setOnClickListener(new View.OnClickListener() { 22 | @Override 23 | public void onClick(View v) { 24 | Intent intent = VedioRecordActivity.startRecordActivity(videoPath,MainActivity.this); 25 | startActivity(intent); 26 | } 27 | }); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /app/src/main/java/com/example/administrator/videorecorddemo/OrientationSensorListener.java: -------------------------------------------------------------------------------- 1 | package com.example.administrator.videorecorddemo; 2 | 3 | import android.hardware.Sensor; 4 | import android.hardware.SensorEvent; 5 | import android.hardware.SensorEventListener; 6 | 7 | public class OrientationSensorListener implements SensorEventListener { 8 | private static final int _DATA_X = 0; 9 | private static final int _DATA_Y = 1; 10 | private static final int _DATA_Z = 2; 11 | 12 | public static final int ORIENTATION_UNKNOWN = -1; 13 | private int orientationHintDegrees; 14 | 15 | 16 | public void onAccuracyChanged(Sensor arg0, int arg1) { 17 | //Auto-generated method stub 18 | 19 | } 20 | 21 | public void onSensorChanged(SensorEvent event) { 22 | float[] values = event.values; 23 | int orientation = ORIENTATION_UNKNOWN; 24 | float X = -values[_DATA_X]; 25 | float Y = -values[_DATA_Y]; 26 | float Z = -values[_DATA_Z]; 27 | float magnitude = X*X + Y*Y; 28 | // Don't trust the angle if the magnitude is small compared to the y value 29 | if (magnitude * 4 >= Z*Z) { 30 | float OneEightyOverPi = 57.29577957855f; 31 | float angle = (float) Math.atan2(-Y, X) * OneEightyOverPi; 32 | orientation = 90 - (int) Math.round(angle); 33 | // normalize to 0 - 359 range 34 | while (orientation >= 360) { 35 | orientation -= 360; 36 | } 37 | while (orientation < 0) { 38 | orientation += 360; 39 | } 40 | } 41 | 42 | if (orientation>45&&orientation<135) { 43 | // 右平行--180 44 | orientationHintDegrees = 180; 45 | }else if (orientation>135&&orientation<225){ 46 | // 倒屏--90 47 | orientationHintDegrees = 90; 48 | }else if (orientation>225&&orientation<315){ 49 | // 左水平-->0 50 | orientationHintDegrees = 0; 51 | }else if ((orientation>315&&orientation<360)||(orientation>0&&orientation<45)){ 52 | //--竖屏--->90 53 | orientationHintDegrees = 90; 54 | } 55 | } 56 | 57 | public int getOrientationHintDegrees() { 58 | return orientationHintDegrees; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /app/src/main/java/com/example/administrator/videorecorddemo/VedioRecordActivity.java: -------------------------------------------------------------------------------- 1 | package com.example.administrator.videorecorddemo; 2 | 3 | import android.app.Activity; 4 | import android.content.Context; 5 | import android.content.Intent; 6 | import android.graphics.Color; 7 | import android.graphics.Rect; 8 | import android.hardware.Sensor; 9 | import android.hardware.SensorManager; 10 | import android.os.Environment; 11 | import android.support.annotation.NonNull; 12 | import android.support.v7.app.AppCompatActivity; 13 | import android.os.Bundle; 14 | import android.view.MotionEvent; 15 | import android.view.View; 16 | import android.widget.Button; 17 | import android.widget.FrameLayout; 18 | import android.widget.TextView; 19 | import android.widget.Toast; 20 | 21 | import java.io.File; 22 | 23 | public class VedioRecordActivity extends AppCompatActivity implements VideoRecordSurface.OnRecordListener{ 24 | 25 | //开始按钮 26 | protected Button btnStart; 27 | protected FrameLayout frameLayout; 28 | //播放进度 29 | protected VideoProgressView videoProgressView; 30 | //按钮提示 31 | protected TextView tvTips; 32 | private int iTime; 33 | private VideoRecordSurface videoRecordSurface; 34 | private String videoSavePath; 35 | public static final String kVideoSavePath = "videoSavePath"; 36 | 37 | private OrientationSensorListener listener; 38 | private SensorManager sm; 39 | private Sensor sensor; 40 | 41 | @Override 42 | protected void onCreate(Bundle savedInstanceState) { 43 | super.onCreate(savedInstanceState); 44 | setContentView(R.layout.activity_vedio_record); 45 | 46 | sm = (SensorManager)getSystemService(Context.SENSOR_SERVICE); 47 | sensor = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); 48 | listener = new OrientationSensorListener(); 49 | sm.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_UI); 50 | 51 | //必须传递的值 52 | videoSavePath = getIntent().getStringExtra(kVideoSavePath); 53 | File file = new File(videoSavePath); 54 | if (!file.exists()) { 55 | file.mkdir(); 56 | } 57 | initView(); 58 | 59 | videoRecordSurface = new VideoRecordSurface(this, videoSavePath); 60 | frameLayout.addView(videoRecordSurface); 61 | btnStart.setOnTouchListener(new View.OnTouchListener() { 62 | private float moveY; 63 | private float moveX; 64 | Rect rect = new Rect(); 65 | boolean isInner = true; 66 | 67 | @Override 68 | public boolean onTouch(View v, MotionEvent event) { 69 | switch (event.getAction()) { 70 | case MotionEvent.ACTION_DOWN: { 71 | //按住事件发生后执行代码的区域 72 | tvTips.setVisibility(View.VISIBLE); 73 | videoRecordSurface.record(VedioRecordActivity.this,listener.getOrientationHintDegrees()); 74 | videoProgressView.startProgress(videoRecordSurface.mRecordMaxTime); 75 | break; 76 | } 77 | case MotionEvent.ACTION_MOVE: { 78 | //移动事件发生后执行代码的区域 79 | if (rect.right == 0 && rect.bottom == 0) { 80 | btnStart.getFocusedRect(rect); 81 | } 82 | moveX = event.getX(); 83 | moveY = event.getY(); 84 | if (moveY > 0 && moveX > 0 && moveX <= rect.right && moveY <= rect.bottom) { 85 | //内 86 | isInner = true; 87 | if (!"移开取消".equals(tvTips.getText().toString().trim())) { 88 | tvTips.setBackgroundColor(Color.TRANSPARENT); 89 | tvTips.setTextColor(getResources().getColor(R.color.video_green)); 90 | tvTips.setText("移开取消"); 91 | } 92 | btnStart.setVisibility(View.INVISIBLE); 93 | } else { 94 | //外 95 | isInner = false; 96 | if (!"松开取消".equals(tvTips.getText().toString().trim())) { 97 | tvTips.setBackgroundColor(Color.RED);//getResources().getColor(android.R.color.holo_red_dark)); 98 | tvTips.setTextColor(Color.WHITE); 99 | tvTips.setText("松开取消"); 100 | } 101 | } 102 | break; 103 | } 104 | case MotionEvent.ACTION_UP: { 105 | //松开事件发生后执行代码的区域 106 | tvTips.setVisibility(View.INVISIBLE); 107 | videoProgressView.stopProgress(); 108 | if (iTime <= videoRecordSurface.mRecordMiniTime || (iTime < videoRecordSurface.mRecordMaxTime && !isInner)) { 109 | if (isInner) { 110 | Toast.makeText(VedioRecordActivity.this, "录制时间太短", Toast.LENGTH_SHORT).show(); 111 | } else { 112 | // 113 | } 114 | videoRecordSurface.stopRecord(); 115 | videoRecordSurface.repCamera(); 116 | btnStart.setVisibility(View.VISIBLE); 117 | } else if(iTime < videoRecordSurface.mRecordMaxTime){ 118 | videoRecordSurface.stop(); 119 | } 120 | break; 121 | } 122 | default: 123 | break; 124 | } 125 | return false; 126 | } 127 | }); 128 | 129 | } 130 | 131 | private void initView() { 132 | btnStart = (Button) findViewById(R.id.libVideoRecorder_btn_start); 133 | frameLayout = (FrameLayout) findViewById(R.id.libVideoRecorder_fl); 134 | videoProgressView = (VideoProgressView) findViewById(R.id.libVideoRecorder_progress); 135 | tvTips = (TextView) findViewById(R.id.libVideoRecorder_tv_tips); 136 | } 137 | 138 | @Override 139 | protected void onStop() { 140 | super.onStop(); 141 | videoRecordSurface.stopRecord(); 142 | finish(); 143 | } 144 | 145 | @Override 146 | protected void onDestroy() { 147 | super.onDestroy(); 148 | } 149 | 150 | 151 | @Override 152 | public void onRecordFinish() { 153 | if (videoProgressView != null) { 154 | videoProgressView.stopProgress(); 155 | } 156 | String recordThumbDir = videoRecordSurface.getRecordThumbDir(); //视频首张照片 157 | String recordMp4Dir = videoRecordSurface.getRecordDir(); //视频播放地址 158 | startActivity(new Intent(this,VideoPlayActivity.class).putExtra(kVideoSavePath, recordMp4Dir)); 159 | } 160 | 161 | @Override 162 | protected void onPause() { 163 | sm.unregisterListener(listener); 164 | super.onPause(); 165 | } 166 | 167 | @Override 168 | protected void onResume() { 169 | sm.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_UI); 170 | super.onResume(); 171 | } 172 | 173 | @Override 174 | public void onRecordProgress(int progress) { 175 | iTime = progress; 176 | } 177 | 178 | 179 | /** 180 | * 开启录制 181 | * 182 | * @param videoPath 小视频录制后存储位置 183 | */ 184 | public static Intent startRecordActivity(@NonNull String videoPath, Activity activity) { 185 | Intent intent = new Intent(activity,VedioRecordActivity.class); 186 | intent.putExtra(kVideoSavePath, videoPath); 187 | return intent; 188 | } 189 | 190 | } 191 | -------------------------------------------------------------------------------- /app/src/main/java/com/example/administrator/videorecorddemo/VideoPlayActivity.java: -------------------------------------------------------------------------------- 1 | package com.example.administrator.videorecorddemo; 2 | 3 | import android.media.MediaPlayer; 4 | import android.support.v7.app.AppCompatActivity; 5 | import android.os.Bundle; 6 | import android.util.Log; 7 | import android.view.View; 8 | import android.widget.TextView; 9 | import android.widget.Toast; 10 | import android.widget.VideoView; 11 | 12 | import java.io.File; 13 | 14 | public class VideoPlayActivity extends AppCompatActivity { 15 | 16 | TextView libPlayVideo_tv_title; 17 | VideoView videoView; 18 | private boolean isFirst = true; 19 | 20 | @Override 21 | protected void onCreate(Bundle savedInstanceState) { 22 | super.onCreate(savedInstanceState); 23 | setContentView(R.layout.activity_video_play); 24 | libPlayVideo_tv_title = (TextView) findViewById(R.id.libPlayVideo_tv_title); 25 | libPlayVideo_tv_title.setText("视频播放"); 26 | videoView = (VideoView) findViewById(R.id.libPlayVideo_videoView); 27 | videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() { 28 | @Override 29 | public boolean onError(MediaPlayer mp, int what, int extra) { 30 | if (isFirst) { 31 | isFirst = false; 32 | Toast.makeText(VideoPlayActivity.this, "播放该视频异常", Toast.LENGTH_SHORT).show(); 33 | } 34 | return true; 35 | } 36 | }); 37 | 38 | String mVideoPath = getIntent().getStringExtra(VedioRecordActivity.kVideoSavePath); 39 | File file = new File(mVideoPath); 40 | if (file.exists()) { 41 | videoView.setVideoPath(file.getAbsolutePath()); 42 | videoView.start(); 43 | setLoop(file.getAbsolutePath()); 44 | } else { 45 | Log.e("tag","not found video " + mVideoPath); 46 | } 47 | } 48 | 49 | public void setLoop(final String videoPath) { 50 | videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { 51 | 52 | @Override 53 | public void onPrepared(MediaPlayer mp) { 54 | mp.start(); 55 | mp.setLooping(true); 56 | 57 | } 58 | }); 59 | videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { 60 | @Override 61 | public void onCompletion(MediaPlayer mp) { 62 | videoView.setVideoPath(videoPath); 63 | videoView.start(); 64 | } 65 | }); 66 | } 67 | 68 | public void videoPlayClick(View view){ 69 | switch (view.getId()){ 70 | case R.id.libPlayVideo_tv_cancel: 71 | finish(); 72 | break; 73 | case R.id.libPlayVideo_tv_more: 74 | Toast.makeText(this, "更多", Toast.LENGTH_SHORT).show(); 75 | break; 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /app/src/main/java/com/example/administrator/videorecorddemo/VideoProgressView.java: -------------------------------------------------------------------------------- 1 | package com.example.administrator.videorecorddemo; 2 | 3 | import android.content.Context; 4 | import android.graphics.Canvas; 5 | import android.graphics.Color; 6 | import android.graphics.Paint; 7 | import android.os.Handler; 8 | import android.os.Looper; 9 | import android.os.SystemClock; 10 | import android.util.AttributeSet; 11 | import android.view.View; 12 | 13 | 14 | /** 15 | * Created by zwj on 2016/7/11. 16 | * 自定义视频录制进度条 17 | */ 18 | public class VideoProgressView extends View { 19 | private Paint mProgressPaint;//进度条的画笔 20 | private int mProgress = 0;//进度条 21 | private int mHeight; 22 | private int mWidth; 23 | private Handler mHandler; 24 | 25 | public VideoProgressView(Context context) { 26 | this(context, null); 27 | } 28 | 29 | public VideoProgressView(Context context, AttributeSet attrs) { 30 | this(context, attrs, -1); 31 | } 32 | 33 | public VideoProgressView(Context context, AttributeSet attrs, int defStyleAttr) { 34 | super(context, attrs, defStyleAttr); 35 | setBackgroundColor(Color.TRANSPARENT); 36 | mHandler = new Handler(Looper.getMainLooper()); 37 | } 38 | 39 | 40 | private Paint getDefaultPaint() { 41 | if (mProgressPaint == null) { 42 | mProgressPaint = new Paint(); 43 | mProgressPaint.setAntiAlias(true); 44 | mProgressPaint.setColor(Color.GREEN); 45 | mProgressPaint.setStyle(Paint.Style.FILL_AND_STROKE); 46 | mProgressPaint.setStrokeWidth(mHeight * 2); 47 | } 48 | return mProgressPaint; 49 | } 50 | 51 | @Override 52 | protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 53 | mWidth = measureWidth(widthMeasureSpec); 54 | mHeight = measureHeight(heightMeasureSpec); 55 | setMeasuredDimension(widthMeasureSpec, heightMeasureSpec); 56 | } 57 | 58 | private int measureWidth(int widthMeasureSpec) { 59 | int width; 60 | int widthMode = MeasureSpec.getMode(widthMeasureSpec); 61 | int widthSize = MeasureSpec.getSize(widthMeasureSpec); 62 | if (widthMode == MeasureSpec.EXACTLY) { 63 | // Parent has told us how big to be. So be it. 64 | width = widthSize; 65 | } else { 66 | width = 200; 67 | if (widthMode == MeasureSpec.AT_MOST) { 68 | width = Math.min(width, widthSize); 69 | } 70 | } 71 | return width; 72 | } 73 | 74 | private int measureHeight(int heightMeasureSpec) { 75 | int height; 76 | int heightMode = MeasureSpec.getMode(heightMeasureSpec); 77 | int heightSize = MeasureSpec.getSize(heightMeasureSpec); 78 | if (heightMode == MeasureSpec.EXACTLY) { 79 | // Parent has told us how big to be. So be it. 80 | height = heightSize; 81 | } else { 82 | height = 50; 83 | if (heightMode == MeasureSpec.AT_MOST) { 84 | height = Math.min(heightMeasureSpec, height); 85 | } 86 | } 87 | return height; 88 | } 89 | 90 | @Override 91 | protected void onDraw(Canvas canvas) { 92 | super.onDraw(canvas); 93 | float startX = mProgress; 94 | float startY = mHeight; 95 | float stopX = mWidth - mProgress; 96 | float stopY = mHeight; 97 | canvas.drawLine(startX, startY, stopX, stopY, getDefaultPaint()); 98 | } 99 | 100 | /** 101 | * 设置进度条 102 | * 103 | * @param second 秒 104 | */ 105 | public void startProgress(final int second) { 106 | isProgress = true; 107 | setVisibility(VISIBLE); 108 | new Thread(new Runnable() { 109 | @Override 110 | public void run() { 111 | int count = mWidth / 2; 112 | int sleepTime = second * 1000 / count; 113 | for (int i = 0; i < count; i++) { 114 | 115 | if ((i == count - 1) || !isProgress) { 116 | mHandler.post(new Runnable() { 117 | @Override 118 | public void run() { 119 | setVisibility(INVISIBLE); 120 | } 121 | }); 122 | break; 123 | } else { 124 | mProgress = i; 125 | postInvalidate(); 126 | SystemClock.sleep(sleepTime); 127 | } 128 | 129 | 130 | } 131 | } 132 | }).start(); 133 | } 134 | 135 | private boolean isProgress; 136 | 137 | public void stopProgress() { 138 | isProgress = false; 139 | } 140 | 141 | } -------------------------------------------------------------------------------- /app/src/main/java/com/example/administrator/videorecorddemo/VideoRecordSurface.java: -------------------------------------------------------------------------------- 1 | package com.example.administrator.videorecorddemo; 2 | 3 | import android.content.Context; 4 | import android.graphics.Bitmap; 5 | import android.hardware.Camera; 6 | import android.media.CamcorderProfile; 7 | import android.media.MediaMetadataRetriever; 8 | import android.media.MediaRecorder; 9 | import android.util.AttributeSet; 10 | import android.util.Log; 11 | import android.view.SurfaceHolder; 12 | import android.view.SurfaceView; 13 | 14 | import java.io.BufferedOutputStream; 15 | import java.io.File; 16 | import java.io.FileOutputStream; 17 | import java.io.IOException; 18 | import java.util.List; 19 | import java.util.Timer; 20 | import java.util.TimerTask; 21 | 22 | /** 23 | * Created by shuwen on 2016/6/22. 24 | * 录像 25 | */ 26 | public class VideoRecordSurface extends SurfaceView implements SurfaceHolder.Callback, MediaRecorder.OnErrorListener { 27 | private final String TAG = this.getClass().getSimpleName(); 28 | private Camera mCamera; 29 | private Context mContext; 30 | private SurfaceHolder mSurfaceHolder; 31 | private File mRecordFile;//存储的路径 32 | private MediaRecorder mMediaRecorder; 33 | private int mTimeCount = 1;//开启时间 34 | public final int mRecordMaxTime = 6;//最大时间 35 | public final int mRecordMiniTime = 2;//最小时间 36 | private Timer mTimer; 37 | private OnRecordListener mOnRecordListener; 38 | private String basePath;//默认路径 39 | private Camera.Size size; 40 | 41 | public VideoRecordSurface(Context context, String videoSavePath) { 42 | this(context, null, videoSavePath); 43 | } 44 | 45 | public VideoRecordSurface(Context context, AttributeSet attrs, String videoSavePath) { 46 | this(context, attrs, -1, videoSavePath); 47 | } 48 | 49 | public VideoRecordSurface(Context context, AttributeSet attrs, int defStyleAttr, String videoSavePath) { 50 | super(context, attrs, defStyleAttr); 51 | basePath = videoSavePath; 52 | this.mContext = context; 53 | mSurfaceHolder = getHolder(); 54 | mSurfaceHolder.addCallback(this); 55 | mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); 56 | initCamera(); 57 | } 58 | 59 | 60 | @Override 61 | public void surfaceCreated(SurfaceHolder holder) { 62 | initCamera(); 63 | } 64 | 65 | @Override 66 | public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { 67 | if (mSurfaceHolder.getSurface() == null) { 68 | return; 69 | } 70 | try { 71 | mCamera.stopPreview(); 72 | mCamera.setDisplayOrientation(90); 73 | mCamera.startPreview(); 74 | mCamera.setPreviewDisplay(mSurfaceHolder); 75 | } catch (Exception ex) { 76 | ex.printStackTrace(); 77 | } 78 | } 79 | 80 | @Override 81 | public void surfaceDestroyed(SurfaceHolder holder) { 82 | stop(); 83 | } 84 | 85 | @Override 86 | public void onError(MediaRecorder mr, int what, int extra) { 87 | try { 88 | if (mr != null) 89 | mr.reset(); 90 | } catch (Exception e) { 91 | e.printStackTrace(); 92 | } 93 | } 94 | 95 | public void repCamera() { 96 | initCamera(); 97 | } 98 | 99 | /** 100 | * 初始化摄像头 101 | * 102 | * @throws IOException 103 | * @author zwj 104 | * @date 2016-06-21 105 | */ 106 | private void initCamera() { 107 | if (mCamera != null) { 108 | freeCameraResource(); 109 | } 110 | try { 111 | mCamera = Camera.open(); 112 | if (mCamera == null) 113 | return; 114 | initParameters(); 115 | mCamera.setDisplayOrientation(90);//竖屏显示 116 | mCamera.setPreviewDisplay(mSurfaceHolder); 117 | mCamera.startPreview(); 118 | mCamera.unlock(); 119 | } catch (Exception e) { 120 | e.printStackTrace(); 121 | freeCameraResource(); 122 | } 123 | } 124 | 125 | private void initParameters() { 126 | CamcorderProfile mProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_1080P); 127 | Camera.Parameters mParams = mCamera.getParameters(); 128 | mParams.setPreviewSize(mProfile.videoFrameWidth, mProfile.videoFrameHeight); 129 | size = mParams.getPreviewSize(); 130 | List focusModes = mParams.getSupportedFocusModes(); 131 | if (focusModes.contains("continuous-video")) { 132 | mParams.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO); 133 | } 134 | mCamera.setParameters(mParams); 135 | } 136 | 137 | /** 138 | * 释放摄像头资源 139 | * 140 | * @author zwj 141 | * @date 2016-06-21 142 | */ 143 | private void freeCameraResource() { 144 | if (mCamera != null) { 145 | mCamera.setPreviewCallback(null); 146 | mCamera.stopPreview(); 147 | mCamera.lock(); 148 | mCamera.release(); 149 | mCamera = null; 150 | } 151 | } 152 | 153 | 154 | /** 155 | * 开始录制视频 156 | * 157 | * @param onRecordListener 回调接口,结束和录像进度 158 | * @author zwj 159 | * @date 2016-06-21 160 | */ 161 | public void record(final OnRecordListener onRecordListener,int orientationHintDegrees) { 162 | this.mOnRecordListener = onRecordListener; 163 | createRecordDir(); 164 | try { 165 | initRecord(orientationHintDegrees); 166 | // 时间计数器重新赋值 167 | mTimeCount = 1; 168 | mTimer = new Timer(); 169 | mTimer.schedule(new TimerTask() { 170 | @Override 171 | public void run() { 172 | // 设置进度条 173 | mOnRecordListener.onRecordProgress(mTimeCount); 174 | if (mTimeCount >= mRecordMaxTime) {// 达到指定时间,停止拍摄 175 | stop(); 176 | } 177 | mTimeCount++; 178 | } 179 | }, 0, 1000); 180 | } catch (Exception e) { 181 | e.printStackTrace(); 182 | } 183 | } 184 | 185 | private Bitmap getVideoThumbnail(String filePath) { 186 | File file = new File(filePath); 187 | if (!file.exists()) { 188 | return null; 189 | } 190 | Bitmap bitmap = null; 191 | Log.i("tag",filePath); 192 | MediaMetadataRetriever retriever = new MediaMetadataRetriever(); 193 | try { 194 | retriever.setDataSource(filePath); 195 | bitmap = retriever.getFrameAtTime(); 196 | } catch (IllegalArgumentException e) { 197 | e.printStackTrace(); 198 | } finally { 199 | try { 200 | retriever.release(); 201 | } catch (RuntimeException e) { 202 | e.printStackTrace(); 203 | } 204 | } 205 | return bitmap; 206 | } 207 | 208 | private void saveBitmapFile(String path, String name, Bitmap bitmap) { 209 | File file = new File(path, name);//将要保存图片的路径 210 | try { 211 | BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file)); 212 | bitmap.compress(Bitmap.CompressFormat.JPEG, 70, bos); 213 | bos.flush(); 214 | bos.close(); 215 | } catch (IOException e) { 216 | e.printStackTrace(); 217 | } 218 | } 219 | 220 | /** 221 | * 初始化 222 | * 223 | * @throws IOException 224 | * @author zwj 225 | * @date 2016-06-21 226 | */ 227 | private void initRecord(int orientationHintDegrees) { 228 | try { 229 | if (mMediaRecorder == null) { 230 | mMediaRecorder = new MediaRecorder(); 231 | mMediaRecorder.setOnErrorListener(this); 232 | } else { 233 | mMediaRecorder.reset(); 234 | } 235 | //1.设置摄像头解锁,和MediaRecorder 236 | mMediaRecorder.setCamera(mCamera); 237 | mMediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface()); 238 | //2.设置视频源 239 | mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); 240 | mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); 241 | //设置视频输出的格式和编码 242 | mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); 243 | CamcorderProfile mProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_480P); 244 | //设置视频的分辨率 245 | mMediaRecorder.setVideoSize(mProfile.videoFrameWidth, mProfile.videoFrameHeight); 246 | mMediaRecorder.setAudioEncodingBitRate(44100); 247 | if (mProfile.videoBitRate > 2 * 1024 * 1024) { 248 | mMediaRecorder.setVideoEncodingBitRate(2 * 1024 * 1024); 249 | } else { 250 | mMediaRecorder.setVideoEncodingBitRate(mProfile.videoBitRate); 251 | } 252 | mMediaRecorder.setVideoFrameRate(mProfile.videoFrameRate); 253 | mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC); 254 | mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264); 255 | if (orientationHintDegrees != 0 && 256 | orientationHintDegrees != 90 && 257 | orientationHintDegrees != 180 && 258 | orientationHintDegrees != 270){ 259 | orientationHintDegrees = 90; 260 | } 261 | mMediaRecorder.setOrientationHint(orientationHintDegrees);// 输出旋转90度,保持竖屏录制 262 | //3.设置输出 263 | mMediaRecorder.setOutputFile(mRecordFile.getAbsolutePath()); 264 | mMediaRecorder.prepare(); 265 | 266 | mMediaRecorder.start(); 267 | } catch (Exception e) { 268 | e.printStackTrace(); 269 | } 270 | } 271 | 272 | private boolean isFirst = true; 273 | /** 274 | * 停止拍摄 275 | * 276 | * @author zwj 277 | * @date 2016-06-21 278 | */ 279 | public void stop() { 280 | stopRecord(); 281 | releaseRecord(); 282 | freeCameraResource(); 283 | if (mTimeCount > mRecordMiniTime) { 284 | saveBitmapFile(basePath, mRecordFile.getName() + ".jpg", getVideoThumbnail(getRecordDir())); 285 | if (mOnRecordListener != null) { 286 | if(isFirst){ 287 | mOnRecordListener.onRecordFinish(); 288 | isFirst = false; 289 | } 290 | } 291 | } 292 | } 293 | 294 | /** 295 | * 释放资源 296 | * 297 | * @author zwj 298 | * @date 2016-06-21 299 | */ 300 | private void releaseRecord() { 301 | if (mMediaRecorder != null) { 302 | mMediaRecorder.setOnErrorListener(null); 303 | try { 304 | mMediaRecorder.release(); 305 | } catch (Exception e) { 306 | e.printStackTrace(); 307 | } 308 | } 309 | mMediaRecorder = null; 310 | } 311 | 312 | /** 313 | * 停止录制 314 | * 315 | * @author zwj 316 | * @date 2016-06-21 317 | */ 318 | public void stopRecord() { 319 | if (mTimer != null) { 320 | mTimer.cancel(); 321 | } 322 | if (mMediaRecorder != null) { 323 | // 设置后不会崩 324 | mMediaRecorder.setOnErrorListener(null); 325 | mMediaRecorder.setPreviewDisplay(null); 326 | try { 327 | mMediaRecorder.stop(); 328 | } catch (Exception e) { 329 | e.printStackTrace(); 330 | } 331 | } 332 | } 333 | 334 | /** 335 | * 设置视频路径 336 | */ 337 | private void createRecordDir() { 338 | File sampleDir = new File(basePath); 339 | if (!sampleDir.exists()) { 340 | sampleDir.mkdirs(); 341 | } 342 | File videoFile = sampleDir; 343 | // 创建文件 344 | try { 345 | //mp4格式 346 | mRecordFile = File.createTempFile(String.valueOf(System.currentTimeMillis()), ".mp4", videoFile); 347 | } catch (IOException e) { 348 | e.printStackTrace(); 349 | } 350 | } 351 | 352 | public String getRecordDir() { 353 | if (mRecordFile == null) { 354 | return ""; 355 | } 356 | return mRecordFile.getPath(); 357 | } 358 | 359 | public String getRecordThumbDir() { 360 | if (mRecordFile == null) { 361 | return ""; 362 | } 363 | return mRecordFile.getPath() + ".jpg"; 364 | } 365 | 366 | 367 | /** 368 | * 录制完成回调接口 369 | * 370 | * @author liuyinjun 371 | * @date 2015-2-5 372 | */ 373 | public interface OnRecordListener { 374 | void onRecordFinish(); 375 | 376 | /** 377 | * 录制进度 378 | */ 379 | void onRecordProgress(int progress); 380 | } 381 | 382 | @Override 383 | protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 384 | float ratio = 1f * size.height / size.width; 385 | int width = MeasureSpec.getSize(widthMeasureSpec); 386 | int height = (int) (width / ratio); 387 | int wms = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY); 388 | int hms = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); 389 | super.onMeasure(wms, hms); 390 | } 391 | } 392 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/libvideo_recorder_default.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 11 | 14 | 17 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/title_left_arrow_white.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Soon-gz/VideoRecord/103e59dfc76b432c1e8c0574f9b4792e55a1e656/app/src/main/res/drawable/title_left_arrow_white.png -------------------------------------------------------------------------------- /app/src/main/res/drawable/title_more_white.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Soon-gz/VideoRecord/103e59dfc76b432c1e8c0574f9b4792e55a1e656/app/src/main/res/drawable/title_more_white.png -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 |