├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ ├── colors.xml
│ │ │ │ ├── dimens.xml
│ │ │ │ └── styles.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
│ │ │ └── layout
│ │ │ │ └── activity_main.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── com
│ │ │ └── yph
│ │ │ └── camerasurfaceview
│ │ │ ├── FileUtil.java
│ │ │ ├── CheckPermissionsUtil.java
│ │ │ ├── CamParaUtil.java
│ │ │ ├── MainActivity.java
│ │ │ └── CameraSurfaceView.java
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── cjt2325
│ │ │ └── cameraview
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── cjt2325
│ │ └── cameraview
│ │ └── ApplicationTest.java
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── .idea
├── copyright
│ └── profiles_settings.xml
├── encodings.xml
├── modules.xml
├── gradle.xml
├── compiler.xml
└── misc.xml
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── screenshot
└── CameraSurfaceView.png
├── .gitignore
├── gradle.properties
├── README.md
├── gradlew.bat
└── gradlew
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------
/.idea/copyright/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | CameraSurfaceView
3 |
4 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/y-grey/CameraSurfaceView-master/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/screenshot/CameraSurfaceView.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/y-grey/CameraSurfaceView-master/HEAD/screenshot/CameraSurfaceView.png
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/workspace.xml
5 | /.idea/libraries
6 | .DS_Store
7 | /build
8 | /captures
9 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/y-grey/CameraSurfaceView-master/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/y-grey/CameraSurfaceView-master/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/y-grey/CameraSurfaceView-master/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/y-grey/CameraSurfaceView-master/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/y-grey/CameraSurfaceView-master/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Wed Mar 01 20:51:02 CST 2017
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | #distributionUrl=file:///D:/gradle_offline/gradle-2.14.1-all.zip
7 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip
8 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/app/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/app/src/test/java/com/cjt2325/cameraview/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.cjt2325.cameraview;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * To work on unit tests, switch the Test Artifact in the Build Variants view.
9 | */
10 | public class ExampleUnitTest {
11 | @Test
12 | public void addition_isCorrect() throws Exception {
13 | assertEquals(4, 2 + 2);
14 | }
15 | }
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/cjt2325/cameraview/ApplicationTest.java:
--------------------------------------------------------------------------------
1 | package com.cjt2325.cameraview;
2 |
3 | import android.app.Application;
4 | import android.test.ApplicationTestCase;
5 |
6 | /**
7 | * Testing Fundamentals
8 | */
9 | public class ApplicationTest extends ApplicationTestCase {
10 | public ApplicationTest() {
11 | super(Application.class);
12 | }
13 | }
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
16 |
17 |
--------------------------------------------------------------------------------
/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:\AndroidStudio\AndroidSDK/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/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 23
5 | buildToolsVersion "24.0.0"
6 |
7 | defaultConfig {
8 | applicationId "com.yph.camerasurfaceview"
9 | minSdkVersion 14
10 | targetSdkVersion 22
11 | versionCode 1
12 | versionName "1.0"
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(include: ['*.jar'], dir: 'libs')
24 | testCompile 'junit:junit:4.12'
25 | compile 'com.android.support:appcompat-v7:23.4.0'
26 | }
27 |
--------------------------------------------------------------------------------
/.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 |
--------------------------------------------------------------------------------
/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 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # CameraSurfaceView
2 | ## 控件介绍
3 | 主要的功能有:拍照,录像,闪光灯,定时长录像 ,前后摄像头的切换,自适应横竖屏的切换,并且支持在后台完成以上所有操作
4 |
5 |
6 | ## 示例截图
7 |
8 | 
9 |
10 |
11 | ## 使用方法
12 |
13 | ```
14 | 1.赋予程序必要的权限;
15 |
16 | 2.布局文件中添加
17 |
18 |
22 |
23 | 或者 new CameraSurfaceView(context),即可。
24 |
25 | 3.拍照:cameraSurfaceView.capture();
26 |
27 | 录像:cameraSurfaceView.startRecord();//开始录制
28 | cameraSurfaceView.stopRecord(); //结束录制
29 | //设置录制时长为10秒视频
30 | cameraSurfaceView.startRecord(10000, new MediaRecorder.OnInfoListener() {
31 | @Override
32 | public void onInfo(MediaRecorder mr, int what, int extra) {
33 | cameraSurfaceView.stopRecord();
34 | }
35 | });
36 |
37 | 闪光灯:cameraSurfaceView.switchLight(boolean open);
38 |
39 | 前后摄像头的切换:cameraSurfaceView.setDefaultCamera(boolean backCamera);
40 |
41 | 前后台切换:cameraSurfaceView.setRunBack(boolean b)
42 |
43 | 4.释放Camera:
44 | @Override
45 | protected void onDestroy() {
46 | super.onDestroy();
47 | cameraSurfaceView.closeCamera();
48 | }
49 |
50 | ```
51 | ## Detail
52 | http://blog.csdn.net/u012874222/article/details/70216700
--------------------------------------------------------------------------------
/app/src/main/java/com/yph/camerasurfaceview/FileUtil.java:
--------------------------------------------------------------------------------
1 | package com.yph.camerasurfaceview;
2 |
3 | import android.graphics.Bitmap;
4 | import android.os.Environment;
5 |
6 | import java.io.BufferedOutputStream;
7 | import java.io.FileOutputStream;
8 | import java.io.IOException;
9 | import java.text.SimpleDateFormat;
10 | import java.util.Date;
11 |
12 | public class FileUtil {
13 | private static final String rootPath = Environment.getExternalStorageDirectory().getAbsolutePath();
14 |
15 | //保存照片
16 | public static void saveBitmap(Bitmap b) {
17 | String jpegName = rootPath + "/" + getTime() + ".jpg";
18 | try {
19 | FileOutputStream fout = new FileOutputStream(jpegName);
20 | BufferedOutputStream bos = new BufferedOutputStream(fout);
21 | b.compress(Bitmap.CompressFormat.JPEG, 100, bos);
22 | bos.flush();
23 | bos.close();
24 | } catch (IOException e) {
25 | e.printStackTrace();
26 | }
27 | }
28 |
29 | //获取视频存储路径
30 | public static String getMediaOutputPath() {
31 | return rootPath + "/" + getTime() + ".mp4";
32 | }
33 |
34 | private static String getTime() {
35 | return new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date(System.currentTimeMillis()));
36 | }
37 |
38 | public static boolean isExternalStorageWritable() {
39 | String state = Environment.getExternalStorageState();
40 | if (Environment.MEDIA_MOUNTED.equals(state)) {
41 | return true;
42 | }
43 | return false;
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/app/src/main/java/com/yph/camerasurfaceview/CheckPermissionsUtil.java:
--------------------------------------------------------------------------------
1 | package com.yph.camerasurfaceview;
2 |
3 | import android.Manifest;
4 | import android.app.Activity;
5 | import android.content.Context;
6 | import android.content.pm.PackageManager;
7 | import android.os.Build;
8 | import android.support.v4.app.ActivityCompat;
9 | import android.util.Log;
10 |
11 | public class CheckPermissionsUtil {
12 | public static final String TAG = "CheckPermissionsUtil";
13 |
14 | Context mContext;
15 |
16 | public CheckPermissionsUtil(Context mContext) {
17 | this.mContext = mContext;
18 | }
19 |
20 | private String[] needPermissions = {
21 | Manifest.permission.RECORD_AUDIO,
22 | Manifest.permission.WAKE_LOCK,
23 | Manifest.permission.CAMERA,
24 | Manifest.permission.WRITE_EXTERNAL_STORAGE,
25 | Manifest.permission.WRITE_SETTINGS
26 | };
27 |
28 | private boolean checkPermission(String... needPermissions) {
29 | for (String permission : needPermissions) {
30 | if (ActivityCompat.checkSelfPermission(mContext, permission) != PackageManager.PERMISSION_GRANTED) {
31 | return false;
32 | }
33 | }
34 | return true;
35 | }
36 |
37 | private void requestPermission(Activity activity, int code, String... needPermissions) {
38 | ActivityCompat.requestPermissions(activity, needPermissions, code);
39 | Log.i(TAG, "request Permission...");
40 | }
41 | public void requestAllPermission(Activity activity) {
42 | if (Build.VERSION.SDK_INT >= 23 && activity.getApplicationInfo().targetSdkVersion >= 23) {
43 | Log.i(TAG, "request All Permission...");
44 | for (String permission : needPermissions) {
45 | if (!checkPermission(permission)) {
46 | requestPermission(activity, 0, permission);
47 | }
48 | }
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
11 |
12 |
17 |
18 |
19 |
27 |
28 |
36 |
37 |
44 |
45 |
53 |
54 |
62 |
63 |
64 |
65 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/app/src/main/java/com/yph/camerasurfaceview/CamParaUtil.java:
--------------------------------------------------------------------------------
1 | package com.yph.camerasurfaceview;
2 |
3 | import android.hardware.Camera.Size;
4 |
5 | import java.util.Collections;
6 | import java.util.Comparator;
7 | import java.util.List;
8 |
9 | public class CamParaUtil {
10 |
11 | public static Size getSize(List list, int th,Size defaultSize) {
12 | if(null == list || list.isEmpty()) return defaultSize;
13 | Collections.sort(list, new Comparator(){
14 | public int compare(Size lhs, Size rhs) {//作升序排序
15 | if (lhs.width == rhs.width) {
16 | return 0;
17 | } else if (lhs.width > rhs.width) {
18 | return 1;
19 | } else {
20 | return -1;
21 | }
22 | }
23 | });
24 | int i = 0;
25 | for (Size s : list) {
26 | if ((s.width > th) ) {//&& equalRate(s, rate)
27 | break;
28 | }
29 | i++;
30 | }
31 | if (i == list.size()) {
32 | return list.get(i-1);
33 | } else {
34 | return list.get(i);
35 | }
36 | }
37 |
38 |
39 | // public static Size getBestSize(List list, float rate) {
40 | // float previewDisparity = 100;
41 | // int index = 0;
42 | // for (int i = 0; i < list.size(); i++) {
43 | // Size cur = list.get(i);
44 | // float prop = (float) cur.width / (float) cur.height;
45 | // if (Math.abs(rate - prop) < previewDisparity) {
46 | // previewDisparity = Math.abs(rate - prop);
47 | // index = i;
48 | // }
49 | // }
50 | // return list.get(index);
51 | // }
52 | //
53 | //
54 | // private static boolean equalRate(Size s, float rate) {
55 | // float r = (float) (s.width) / (float) (s.height);
56 | // if (Math.abs(r - rate) <= 0.2) {
57 | // return true;
58 | // } else {
59 | // return false;
60 | // }
61 | // }
62 |
63 | public static boolean isSupportedFocusMode(List focusList, String focusMode) {
64 | for (int i = 0; i < focusList.size(); i++) {
65 | if (focusMode.equals(focusList.get(i))) {
66 | return true;
67 | }
68 | }
69 | return false;
70 | }
71 |
72 | public static boolean isSupportedFormats(List supportedFormats, int jpeg) {
73 | for (int i = 0; i < supportedFormats.size(); i++) {
74 | if (jpeg == supportedFormats.get(i)) {
75 | return true;
76 | }
77 | }
78 | return false;
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 | 1.7
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
--------------------------------------------------------------------------------
/app/src/main/java/com/yph/camerasurfaceview/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.yph.camerasurfaceview;
2 |
3 | import android.os.Bundle;
4 | import android.support.v7.app.AppCompatActivity;
5 | import android.view.View;
6 | import android.widget.CompoundButton;
7 | import android.widget.ToggleButton;
8 |
9 | public class MainActivity extends AppCompatActivity {
10 | private CameraSurfaceView cameraSurfaceView;
11 |
12 | @Override
13 | protected void onCreate(Bundle savedInstanceState) {
14 | super.onCreate(savedInstanceState);
15 | setContentView(R.layout.activity_main);
16 | getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
17 | getSupportActionBar().hide();
18 |
19 | CheckPermissionsUtil checkPermissionsUtil = new CheckPermissionsUtil(this);
20 | checkPermissionsUtil.requestAllPermission(this);
21 |
22 | cameraSurfaceView = (CameraSurfaceView) findViewById(R.id.cameraSurfaceView);
23 | findViewById(R.id.capture).setOnClickListener(new View.OnClickListener() {
24 | @Override
25 | public void onClick(View v) {
26 | cameraSurfaceView.capture();
27 | }
28 | });
29 | ((ToggleButton) findViewById(R.id.record)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
30 | @Override
31 | public void onCheckedChanged(final CompoundButton buttonView, boolean isChecked) {
32 | if (isChecked) {
33 | cameraSurfaceView.startRecord();
34 | //设置录制时长为10秒视频
35 | // cameraSurfaceView.startRecord(10000, new MediaRecorder.OnInfoListener() {
36 | // @Override
37 | // public void onInfo(MediaRecorder mr, int what, int extra) {
38 | // cameraSurfaceView.stopRecord();
39 | // buttonView.setChecked(false);
40 | // }
41 | // });
42 | }
43 | else
44 | cameraSurfaceView.stopRecord();
45 | }
46 | });
47 | ((ToggleButton) findViewById(R.id.light)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
48 | @Override
49 | public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
50 | cameraSurfaceView.switchLight(isChecked);
51 | }
52 | });
53 | ((ToggleButton) findViewById(R.id.runBack)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
54 | @Override
55 | public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
56 | cameraSurfaceView.setRunBack(isChecked);
57 | }
58 | });
59 | ((ToggleButton) findViewById(R.id.switchCamera)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
60 | @Override
61 | public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
62 | cameraSurfaceView.setDefaultCamera(!isChecked);
63 | }
64 | });
65 | }
66 |
67 | @Override
68 | protected void onDestroy() {
69 | super.onDestroy();
70 | cameraSurfaceView.closeCamera();
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/app/src/main/java/com/yph/camerasurfaceview/CameraSurfaceView.java:
--------------------------------------------------------------------------------
1 | package com.yph.camerasurfaceview;
2 |
3 | import android.content.Context;
4 | import android.content.res.Configuration;
5 | import android.graphics.Bitmap;
6 | import android.graphics.BitmapFactory;
7 | import android.graphics.ImageFormat;
8 | import android.graphics.Matrix;
9 | import android.graphics.SurfaceTexture;
10 | import android.hardware.Camera;
11 | import android.media.MediaRecorder;
12 | import android.util.AttributeSet;
13 | import android.view.SurfaceHolder;
14 | import android.view.SurfaceView;
15 | import android.view.View;
16 | import android.widget.Toast;
17 |
18 | import java.io.IOException;
19 |
20 | import static android.hardware.Camera.Parameters.FOCUS_MODE_AUTO;
21 |
22 | public class CameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback, Camera.AutoFocusCallback, View.OnClickListener {
23 |
24 | protected static final int[] VIDEO_320 = {320, 240};
25 | protected static final int[] VIDEO_480 = {640, 480};
26 | protected static final int[] VIDEO_720 = {1280, 720};
27 | protected static final int[] VIDEO_1080 = {1920, 1080};
28 | private int screenOritation = Configuration.ORIENTATION_PORTRAIT;
29 | private boolean mOpenBackCamera = true;
30 | private SurfaceHolder mSurfaceHolder;
31 | private SurfaceTexture mSurfaceTexture;
32 | private boolean mRunInBackground = false;
33 | boolean isAttachedWindow = false;
34 | private Camera mCamera;
35 | private Camera.Parameters mParam;
36 | private byte[] previewBuffer;
37 | private int mCameraId;
38 | protected int previewformat = ImageFormat.NV21;
39 | Context context;
40 |
41 | public CameraSurfaceView(Context context) {
42 | super(context);
43 | init(context);
44 | }
45 |
46 | public CameraSurfaceView(Context context, AttributeSet attrs) {
47 | super(context, attrs);
48 | init(context);
49 | }
50 |
51 | public CameraSurfaceView(Context context, AttributeSet attrs, int defStyle) {
52 | super(context, attrs, defStyle);
53 | init(context);
54 | }
55 |
56 | private void init(Context context) {
57 | this.context = context;
58 | cameraState = CameraState.START;
59 | if (cameraStateListener != null) {
60 | cameraStateListener.onCameraStateChange(cameraState);
61 | }
62 | openCamera();
63 | if (context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
64 | screenOritation = Configuration.ORIENTATION_LANDSCAPE;
65 | }
66 | mSurfaceHolder = getHolder();
67 | mSurfaceHolder.addCallback(this);
68 | mSurfaceTexture = new SurfaceTexture(10);
69 | setOnClickListener(this);
70 | post(new Runnable() {
71 | @Override
72 | public void run() {
73 | if(!isAttachedWindow){
74 | mRunInBackground = true;
75 | startPreview();
76 | }
77 | }
78 | });
79 | }
80 |
81 | @Override
82 | protected void onAttachedToWindow() {
83 | super.onAttachedToWindow();
84 | isAttachedWindow = true;
85 | }
86 |
87 | private void openCamera() {
88 | if (mOpenBackCamera) {
89 | mCameraId = findCamera(false);
90 | } else {
91 | mCameraId = findCamera(true);
92 | }
93 | if (mCameraId == -1) {
94 | mCameraId = 0;
95 | }
96 | try {
97 | mCamera = Camera.open(mCameraId);
98 | } catch (Exception ee) {
99 | mCamera = null;
100 | cameraState = CameraState.ERROR;
101 | if (cameraStateListener != null) {
102 | cameraStateListener.onCameraStateChange(cameraState);
103 | }
104 | }
105 | if (mCamera == null) {
106 | Toast.makeText(context, "打开摄像头失败", Toast.LENGTH_SHORT).show();
107 | return;
108 | }
109 | }
110 |
111 | private int findCamera(boolean front) {
112 | int cameraCount;
113 | try {
114 | Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
115 | cameraCount = Camera.getNumberOfCameras();
116 | for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
117 | Camera.getCameraInfo(camIdx, cameraInfo);
118 | int facing = front ? 1 : 0;
119 | if (cameraInfo.facing == facing) {
120 | return camIdx;
121 | }
122 | }
123 | } catch (Exception e) {
124 | e.printStackTrace();
125 | }
126 | return -1;
127 | }
128 |
129 | public boolean setDefaultCamera(boolean backCamera) {
130 | if (mOpenBackCamera == backCamera) return false;
131 | if (isRecording) {
132 | Toast.makeText(context, "请先结束录像", Toast.LENGTH_SHORT).show();
133 | return false;
134 | }
135 | mOpenBackCamera = backCamera;
136 | if (mCamera != null) {
137 | closeCamera();
138 | openCamera();
139 | startPreview();
140 | }
141 | return true;
142 | }
143 |
144 |
145 | public void closeCamera() {
146 | stopRecord();
147 | stopPreview();
148 | releaseCamera();
149 | }
150 |
151 | private void releaseCamera() {
152 | try {
153 | if (mCamera != null) {
154 | mCamera.setPreviewCallback(null);
155 | mCamera.setPreviewCallbackWithBuffer(null);
156 | mCamera.stopPreview();
157 | mCamera.release();
158 | mCamera = null;
159 | }
160 | } catch (Exception ee) {
161 | }
162 | }
163 |
164 | private boolean isSupportCameraLight() {
165 | boolean mIsSupportCameraLight = false;
166 | try {
167 | if (mCamera != null) {
168 | Camera.Parameters parameter = mCamera.getParameters();
169 | Object a = parameter.getSupportedFlashModes();
170 | if (a == null) {
171 | mIsSupportCameraLight = false;
172 | } else {
173 | mIsSupportCameraLight = true;
174 | }
175 | }
176 | } catch (Exception e) {
177 | mIsSupportCameraLight = false;
178 | e.printStackTrace();
179 | }
180 | return mIsSupportCameraLight;
181 | }
182 |
183 |
184 | private Camera.PreviewCallback previewCallback = new Camera.PreviewCallback() {
185 | public synchronized void onPreviewFrame(byte[] data, Camera camera) {
186 | if (data == null) {
187 | releaseCamera();
188 | return;
189 | }
190 | //you can code media here
191 | if (cameraState != CameraState.PREVIEW) {
192 | cameraState = CameraState.PREVIEW;
193 | if (cameraStateListener != null) {
194 | cameraStateListener.onCameraStateChange(cameraState);
195 | }
196 | }
197 | mCamera.addCallbackBuffer(previewBuffer);
198 | }
199 | };
200 |
201 | //设置Camera各项参数
202 | private void startPreview() {
203 | if (mCamera == null) return;
204 | try {
205 | mParam = mCamera.getParameters();
206 | mParam.setPreviewFormat(previewformat);
207 | mParam.setRotation(0);
208 | Camera.Size previewSize = CamParaUtil.getSize(mParam.getSupportedPreviewSizes(), 1000,
209 | mCamera.new Size(VIDEO_720[0], VIDEO_720[1]));
210 | mParam.setPreviewSize(previewSize.width, previewSize.height);
211 | int yuv_buffersize = previewSize.width * previewSize.height * ImageFormat.getBitsPerPixel(previewformat) / 8;
212 | previewBuffer = new byte[yuv_buffersize];
213 | Camera.Size pictureSize = CamParaUtil.getSize(mParam.getSupportedPictureSizes(), 1500,
214 | mCamera.new Size(VIDEO_1080[0], VIDEO_1080[1]));
215 | mParam.setPictureSize(pictureSize.width, pictureSize.height);
216 | if (CamParaUtil.isSupportedFormats(mParam.getSupportedPictureFormats(), ImageFormat.JPEG)) {
217 | mParam.setPictureFormat(ImageFormat.JPEG);
218 | mParam.setJpegQuality(100);
219 | }
220 | if (CamParaUtil.isSupportedFocusMode(mParam.getSupportedFocusModes(), FOCUS_MODE_AUTO)) {
221 | mParam.setFocusMode(FOCUS_MODE_AUTO);
222 | }
223 | if (screenOritation != Configuration.ORIENTATION_LANDSCAPE) {
224 | mParam.set("orientation", "portrait");
225 | mCamera.setDisplayOrientation(90);
226 | } else {
227 | mParam.set("orientation", "landscape");
228 | mCamera.setDisplayOrientation(0);
229 | }
230 | if (mRunInBackground) {
231 | mCamera.setPreviewTexture(mSurfaceTexture);
232 | mCamera.addCallbackBuffer(previewBuffer);
233 | // mCamera.setPreviewCallbackWithBuffer(previewCallback);//设置摄像头预览帧回调
234 | } else {
235 | mCamera.setPreviewDisplay(mSurfaceHolder);
236 | // mCamera.setPreviewCallback(previewCallback);//设置摄像头预览帧回调
237 | }
238 | mCamera.setParameters(mParam);
239 | mCamera.startPreview();
240 | if (cameraState != CameraState.START) {
241 | cameraState = CameraState.START;
242 | if (cameraStateListener != null) {
243 | cameraStateListener.onCameraStateChange(cameraState);
244 | }
245 | }
246 | } catch (Exception e) {
247 | releaseCamera();
248 | return;
249 | }
250 | try {
251 | String mode = mCamera.getParameters().getFocusMode();
252 | if (("auto".equals(mode)) || ("macro".equals(mode))) {
253 | mCamera.autoFocus(null);
254 | }
255 | } catch (Exception e) {
256 | }
257 | }
258 |
259 | private void stopPreview() {
260 | if (mCamera == null) return;
261 | try {
262 | if (mRunInBackground) {
263 | mCamera.setPreviewCallbackWithBuffer(null);
264 | mCamera.stopPreview();
265 | } else {
266 | mCamera.setPreviewCallback(null);
267 | mCamera.stopPreview();
268 | }
269 | if (cameraState != CameraState.STOP) {
270 | cameraState = CameraState.STOP;
271 | if (cameraStateListener != null) {
272 | cameraStateListener.onCameraStateChange(cameraState);
273 | }
274 | }
275 | } catch (Exception ee) {
276 | }
277 | }
278 |
279 | @Override
280 | public void onClick(View v) {
281 | if (mCamera != null) {
282 | mCamera.autoFocus(null);
283 | }
284 | }
285 |
286 | @Override
287 | public void surfaceCreated(SurfaceHolder holder) {
288 | stopPreview();
289 | startPreview();
290 | }
291 |
292 | @Override
293 | public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
294 | }
295 |
296 | @Override
297 | public void surfaceDestroyed(SurfaceHolder holder) {
298 | stopPreview();
299 | if (mRunInBackground)
300 | startPreview();
301 | }
302 |
303 | protected CameraState cameraState;
304 | private CameraStateListener cameraStateListener;
305 |
306 | public enum CameraState {
307 | START, PREVIEW, STOP, ERROR
308 | }
309 |
310 | public void setOnCameraStateListener(CameraStateListener listener) {
311 | this.cameraStateListener = listener;
312 | }
313 |
314 | public interface CameraStateListener {
315 | void onCameraStateChange(CameraState paramCameraState);
316 | }
317 |
318 | /**
319 | * ___________________________________前/后台运行______________________________________
320 | **/
321 | public void setRunBack(boolean b) {
322 | if (mCamera == null) return;
323 | if (b == mRunInBackground) return;
324 | if(!b && !isAttachedWindow){
325 | Toast.makeText(context, "Vew未依附在Window,无法显示", Toast.LENGTH_SHORT).show();
326 | return;
327 | }
328 | mRunInBackground = b;
329 | if (b)
330 | setVisibility(View.GONE);
331 | else
332 | setVisibility(View.VISIBLE);
333 | }
334 |
335 | /**
336 | * ___________________________________开关闪光灯______________________________________
337 | **/
338 | public void switchLight(boolean open) {
339 | if (mCamera == null) return;
340 | try {
341 | if (mCamera != null) {
342 | if (open) {
343 | Camera.Parameters parameter = mCamera.getParameters();
344 | if (parameter.getFlashMode().equals("off")) {
345 | parameter.setFlashMode("torch");
346 | mCamera.setParameters(parameter);
347 | } else {
348 | parameter.setFlashMode("off");
349 | mCamera.setParameters(parameter);
350 | }
351 | } else {
352 | Camera.Parameters parameter = mCamera.getParameters();
353 | if ((parameter.getFlashMode() != null) &&
354 | (parameter.getFlashMode().equals("torch"))) {
355 | parameter.setFlashMode("off");
356 | mCamera.setParameters(parameter);
357 | }
358 | }
359 | }
360 | } catch (Exception e) {
361 | e.printStackTrace();
362 | }
363 | }
364 |
365 | /**
366 | * ___________________________________以下为拍照模块______________________________________
367 | **/
368 | public void capture() {
369 | if (mCamera == null) return;
370 | if (!FileUtil.isExternalStorageWritable()) {
371 | Toast.makeText(context, "请插入存储卡", Toast.LENGTH_SHORT).show();
372 | return;
373 | }
374 | mCamera.autoFocus(this);
375 | }
376 |
377 | @Override
378 | public void onAutoFocus(boolean success, Camera camera) {
379 | if (success) {
380 | try {
381 | mCamera.takePicture(null, null, new Camera.PictureCallback() {
382 | @Override
383 | public void onPictureTaken(byte[] data, Camera camera) {
384 | Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
385 | Matrix matrix = new Matrix();
386 | if (mOpenBackCamera) {
387 | matrix.setRotate(90);
388 | } else {
389 | matrix.setRotate(270);
390 | matrix.postScale(-1, 1);
391 | }
392 | bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
393 | FileUtil.saveBitmap(bitmap);
394 | Toast.makeText(context, "拍照成功", Toast.LENGTH_SHORT).show();
395 | startPreview();
396 | }
397 | });
398 | } catch (Exception e) {
399 | if (isRecording) {
400 | Toast.makeText(context, "请先结束录像", Toast.LENGTH_SHORT).show();
401 | }
402 | }
403 | }
404 | }
405 |
406 | /**
407 | * ___________________________________以下为视频录制模块______________________________________
408 | **/
409 | MediaRecorder mediaRecorder = new MediaRecorder();
410 | private boolean isRecording = false;
411 |
412 | public boolean isRecording() {
413 | return isRecording;
414 | }
415 |
416 | public boolean startRecord() {
417 | return startRecord(-1, null);
418 | }
419 |
420 | public boolean startRecord(int maxDurationMs, MediaRecorder.OnInfoListener onInfoListener) {
421 | if (mCamera == null) return false;
422 | if (!FileUtil.isExternalStorageWritable()) {
423 | Toast.makeText(context, "请插入存储卡", Toast.LENGTH_SHORT).show();
424 | return false;
425 | }
426 | mCamera.unlock();
427 | mediaRecorder.reset();
428 | mediaRecorder.setCamera(mCamera);
429 | mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
430 | mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
431 | mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
432 | mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
433 | mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
434 | Camera.Size videoSize = CamParaUtil.getSize(mParam.getSupportedVideoSizes(), 1200,
435 | mCamera.new Size(VIDEO_1080[0], VIDEO_1080[1]));
436 | mediaRecorder.setVideoSize(videoSize.width, videoSize.height);
437 | mediaRecorder.setVideoEncodingBitRate(5 * 1024 * 1024);
438 | // mediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());//设置录制预览surface
439 | if (mOpenBackCamera) {
440 | mediaRecorder.setOrientationHint(90);
441 | } else {
442 | if (screenOritation == Configuration.ORIENTATION_LANDSCAPE)
443 | mediaRecorder.setOrientationHint(90);
444 | else
445 | mediaRecorder.setOrientationHint(270);
446 | }
447 | if (maxDurationMs != -1) {
448 | mediaRecorder.setMaxDuration(maxDurationMs);
449 | mediaRecorder.setOnInfoListener(onInfoListener);
450 | }
451 |
452 | mediaRecorder.setOutputFile(FileUtil.getMediaOutputPath());
453 | try {
454 | mediaRecorder.prepare();
455 | mediaRecorder.start();
456 | isRecording = true;
457 | } catch (IOException e) {
458 | e.printStackTrace();
459 | return false;
460 | }
461 | return true;
462 | }
463 |
464 | public void stopRecord() {
465 | if (!isRecording) return;
466 | mediaRecorder.setPreviewDisplay(null);
467 | try {
468 | mediaRecorder.stop();
469 | isRecording = false;
470 | Toast.makeText(context, "视频已保存在根目录", Toast.LENGTH_SHORT).show();
471 | } catch (IllegalStateException e) {
472 | e.printStackTrace();
473 | }
474 | }
475 |
476 | /**_________________________________________________________________________________________**/
477 |
478 |
479 | }
480 |
--------------------------------------------------------------------------------