Repository: lingochamp/LingoRecorder Branch: master Commit: 82a711ce30c4 Files: 69 Total size: 143.5 KB Directory structure: gitextract_ebpvroic/ ├── .gitignore ├── LICENSE.txt ├── README.md ├── build.gradle ├── build_aar.sh ├── demo/ │ ├── build.gradle │ ├── proguard-rules.pro │ └── src/ │ ├── androidTest/ │ │ └── java/ │ │ └── com/ │ │ └── liulishuo/ │ │ └── engzo/ │ │ └── lingorecorder/ │ │ └── ExampleInstrumentedTest.java │ ├── main/ │ │ ├── AndroidManifest.xml │ │ ├── java/ │ │ │ └── com/ │ │ │ └── liulishuo/ │ │ │ └── engzo/ │ │ │ └── lingorecorder/ │ │ │ └── demo/ │ │ │ ├── AndroidFlacProcessor.java │ │ │ ├── LocalScorerProcessor.java │ │ │ ├── RecordPermissionHelper.java │ │ │ ├── ScorerService.java │ │ │ ├── Utils.java │ │ │ ├── activity/ │ │ │ │ ├── AcrossProcessDemonstrateActivity.java │ │ │ │ ├── DemoListActivity.java │ │ │ │ ├── FlacDemonstrateActivity.java │ │ │ │ ├── ProcessorsDemonstrateActivity.java │ │ │ │ ├── RecordActivity.java │ │ │ │ ├── RecordDemonstrateActivity.java │ │ │ │ └── VolumeDemonstrateActivity.java │ │ │ └── view/ │ │ │ └── VolumeView.java │ │ └── res/ │ │ ├── layout/ │ │ │ ├── activity_across_process_demonstrate.xml │ │ │ ├── activity_demo_list.xml │ │ │ ├── activity_flac_demonstrate.xml │ │ │ ├── activity_processors_demonstrate.xml │ │ │ ├── activity_record_demonstrate.xml │ │ │ └── activity_volume.xml │ │ └── values/ │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test/ │ └── java/ │ └── com/ │ └── liulishuo/ │ └── engzo/ │ └── lingorecorder/ │ └── ExampleUnitTest.java ├── gradle/ │ ├── bintray.gradle │ ├── mvn-local.gradle │ ├── mvn-push.gradle │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat ├── library/ │ ├── build.gradle │ ├── gradle.properties │ ├── proguard-rules.pro │ └── src/ │ ├── androidTest/ │ │ ├── AndroidManifest.xml │ │ └── java/ │ │ └── com/ │ │ └── liulishuo/ │ │ └── engzo/ │ │ └── lingorecorder/ │ │ ├── CancelRecordTest.java │ │ ├── LingoRecorderTest.java │ │ └── RecordAndProcessorEndTest.java │ ├── main/ │ │ ├── AndroidManifest.xml │ │ ├── aidl/ │ │ │ └── com/ │ │ │ └── liulishuo/ │ │ │ └── engzo/ │ │ │ └── IAudioProcessorService.aidl │ │ └── java/ │ │ └── com/ │ │ └── liulishuo/ │ │ └── engzo/ │ │ └── lingorecorder/ │ │ ├── LingoRecorder.java │ │ ├── processor/ │ │ │ ├── AudioProcessor.java │ │ │ ├── TimerProcessor.java │ │ │ └── WavProcessor.java │ │ ├── recorder/ │ │ │ ├── AndroidRecorder.java │ │ │ ├── IRecorder.java │ │ │ ├── WavFileRecorder.java │ │ │ └── exception/ │ │ │ ├── RecorderException.java │ │ │ ├── RecorderGetBufferSizeException.java │ │ │ ├── RecorderInitException.java │ │ │ ├── RecorderReadException.java │ │ │ └── RecorderStartException.java │ │ ├── utils/ │ │ │ ├── LOG.java │ │ │ ├── RecorderProperty.java │ │ │ └── WrapBuffer.java │ │ └── volume/ │ │ ├── DefaultVolumeCalculator.java │ │ ├── IVolumeCalculator.java │ │ └── OnVolumeListener.java │ └── test/ │ └── java/ │ └── com/ │ └── liulishuo/ │ └── engzo/ │ └── lingorecorder/ │ └── ExampleUnitTest.java └── settings.gradle ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ # Created by .ignore support plugin (hsz.mobi) build .gradle local.properties .idea/workspace.xml .idea/libraries .idea/misc.xml *.iml ================================================ FILE: LICENSE.txt ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright (c) 2017 LingoChamp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # LingoRecorder LingoRecord is a better recorder for Android, you can easily process pcm data from it. [ ![Download](https://api.bintray.com/packages/wangcongwu123/maven/LingoRecorder/images/download.svg) ](https://bintray.com/wangcongwu123/maven/LingoRecorder/_latestVersion) # Features 1. 多线程机制保证处理能力和 PCM 数据的完整性。 2. 抽象出 AudioProcessor 来注入 Recorder 中以支持录音和处理的分离。 3. 提供 WavFileRecorder 以支持以文件来替代录音器生成录音数据。 4. 提供 aidl 接口方便在另一个进程中处理录音数据。 # Sample ## LingoRecorder 的使用 只需简单的三步操作即可: ``` lingoRecorder = new LingoRecorder(); lingoRecorder.setOnRecordStopListener(new LingoRecorder.OnRecordStopListener() { @Override public void onRecordStop(Throwable throwable, Result result) { //any execeptions occur during recording will be received at here. //you can get duration and output file from Result. } }); lingoRecorder.setOnProcessStopListener(new LingoRecorder.OnProcessStopListener() { @Override public void onProcessStop(Throwable throwable, Map map) { //any execeptions occur during processing will be received at here. //you can get any processors you inject into recorder. //the callback will be invoked after "onRecordStop". } }); ``` 效果图: ![image](https://raw.github.com/lingochamp/LingoRecorder/develop/demo/images/record.gif) ## 自定义 AudioProcessor 的使用 可以实现 AudioProcessor 来自定义自己的处理器: ``` public interface AudioProcessor { void start() throws Exception; void flow(byte[] bytes, int size) throws Exception; boolean needExit(); void end() throws Exception; void release(); } ``` 效果图: ![image](https://raw.github.com/lingochamp/LingoRecorder/develop/demo/images/custom_processors.gif) ## 将 AudioProcessor 运行在一个独立的进程中 LingoRecorder 提供了 aidl 接口以支持在一个独立的进程中运行 AudioProcessor。示例中自定义了一个 `LocalScorerProcessor` 运行在 "score" 进程中。 ## Flac encoder 示例中也演示了一个使用 `MediaCodec` 进行 Flac 编码的 AudioProcessor。此示例是为了向有硬编码需求的用户提供一个样例。 ## 计算/监听音量 设置音量监听器: ``` //只设置 OnVolumeListener 的时候,计算音量的方式使用的是一个默认的内部实现 //内部默认实现的返回值是[0, 90]的分贝值 lingoRecorder.setOnVolumeListener(new OnVolumeListener() { @Override public void onVolume(double volume) { } }); //也可以提供自己的计算音量的实现 lingoRecorder.setOnVolumeListener(new OnVolumeListener() { @Override public void onVolume(double volume) { } }, new IVolumeCalculator() { @Override public double onAudioChunk(byte[] chunk, int size, int bitsPerSample) { return 0; } }); ``` Demo 中提供了相关示例,效果图: ![image](https://raw.github.com/lingochamp/LingoRecorder/develop/demo/images/volume.gif) # 在项目中引用 Gradle: ``` compile 'com.liulishuo.engzo:lingo-recorder:1.2.5' ``` # Pull Request 欢迎各位基于 develop 分支进行 pull request。 License ------- Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: build.gradle ================================================ // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { jcenter() google() } dependencies { classpath 'com.android.tools.build:gradle:3.5.3' classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.8.4' } } allprojects { repositories { jcenter() google() } } subprojects { group = GROUP version = VERSION_NAME } task clean(type: Delete) { delete rootProject.buildDir } ================================================ FILE: build_aar.sh ================================================ ./gradlew clean build generateRelease -p library ================================================ FILE: demo/build.gradle ================================================ apply plugin: 'com.android.application' android { compileSdkVersion 28 defaultConfig { applicationId "com.liulishuo.engzo.lingorecorder.demo" minSdkVersion 15 targetSdkVersion 28 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) androidTestImplementation('androidx.test.espresso:espresso-core:3.1.0', { exclude group: 'com.android.support', module: 'support-annotations' }) implementation project(":lingo-recorder") // compile 'com.liulishuo.engzo:lingo-recorder:1.2.5' implementation 'androidx.appcompat:appcompat:1.1.0' implementation 'androidx.recyclerview:recyclerview:1.1.0' implementation 'androidx.constraintlayout:constraintlayout:1.1.3' testImplementation 'junit:junit:4.12' } ================================================ FILE: demo/proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified # in /Users/wcw/dev/sdk/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the proguardFiles # directive in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # Add any project specific keep options here: # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} # Uncomment this to preserve the line number information for # debugging stack traces. #-keepattributes SourceFile,LineNumberTable # If you keep the line number information, uncomment this to # hide the original source file name. #-renamesourcefileattribute SourceFile ================================================ FILE: demo/src/androidTest/java/com/liulishuo/engzo/lingorecorder/ExampleInstrumentedTest.java ================================================ package com.liulishuo.engzo.lingorecorder; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see Testing documentation */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.liulishuo.engzo.lingorecorder", appContext.getPackageName()); } } ================================================ FILE: demo/src/main/AndroidManifest.xml ================================================ ================================================ FILE: demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/AndroidFlacProcessor.java ================================================ package com.liulishuo.engzo.lingorecorder.demo; import android.media.MediaCodec; import android.media.MediaFormat; import android.os.Build; import androidx.annotation.RequiresApi; import com.liulishuo.engzo.lingorecorder.processor.AudioProcessor; import com.liulishuo.engzo.lingorecorder.utils.LOG; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; /** * Created by wcw on 3/30/17. */ @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) public class AndroidFlacProcessor implements AudioProcessor { private String filePath; private MediaCodec codec; private FileOutputStream fos; public AndroidFlacProcessor() { } public AndroidFlacProcessor(String filePath) { this.filePath = filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } @Override public void start() throws IOException { try { fos = new FileOutputStream(filePath); } catch (Exception e) { e.printStackTrace(); } String mime = "audio/flac"; MediaFormat format = MediaFormat.createAudioFormat(mime, 16000, 1); codec = MediaCodec.createEncoderByType(mime); codec.configure( format, null /* surface */, null /* crypto */, MediaCodec.CONFIGURE_FLAG_ENCODE); codec.start(); } @Override public void flow(byte[] bytes, int size) { try { ByteBuffer[] inputBuffers = codec.getInputBuffers(); ByteBuffer[] outputBuffers = codec.getOutputBuffers(); int inputBufferIndex = codec.dequeueInputBuffer(-1); if (inputBufferIndex >= 0) { ByteBuffer inputBuffer = inputBuffers[inputBufferIndex]; inputBuffer.clear(); inputBuffer.put(bytes); codec.queueInputBuffer(inputBufferIndex, 0, size, 0, 0); } MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo(); int outputBufferIndex = codec.dequeueOutputBuffer(bufferInfo, 0); while (outputBufferIndex >= 0) { ByteBuffer outputBuffer = outputBuffers[outputBufferIndex]; byte[] outData = new byte[bufferInfo.size]; outputBuffer.get(outData); fos.write(outData, 0, outData.length); LOG.d("FlacEncoder " + outData.length + " bytes written"); codec.releaseOutputBuffer(outputBufferIndex, false); outputBufferIndex = codec.dequeueOutputBuffer(bufferInfo, 0); } } catch (Throwable t) { t.printStackTrace(); } } @Override public boolean needExit() { return false; } @Override public void end() { try { if (codec != null) { codec.stop(); codec.release(); codec = null; } if (fos != null) { fos.flush(); fos.close(); fos = null; } } catch (Exception ex) { ex.printStackTrace(); } } public String getFilePath() { return filePath; } @Override public void release() { end(); } } ================================================ FILE: demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/LocalScorerProcessor.java ================================================ package com.liulishuo.engzo.lingorecorder.demo; import android.app.Application; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import com.liulishuo.engzo.IAudioProcessorService; import com.liulishuo.engzo.lingorecorder.processor.AudioProcessor; import com.liulishuo.engzo.lingorecorder.utils.LOG; import java.util.concurrent.CountDownLatch; /** * Created by wcw on 4/14/17. */ public class LocalScorerProcessor implements AudioProcessor { private boolean mBound = false; private IAudioProcessorService scorerService; private CountDownLatch countDownLatch; private boolean hasRelease = false; private Application application = null; private String spokenText; private int score; public LocalScorerProcessor(Application application, String spokenText) { this.spokenText = spokenText; this.application = application; } private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { mBound = true; scorerService = IAudioProcessorService.Stub.asInterface(service); countDownLatch.countDown(); // avoid ActivityManager: Scheduling restart of crashed service if (hasRelease) { application.unbindService(this); mBound = false; } LOG.d("localScorer onServiceConnected"); } @Override public void onServiceDisconnected(ComponentName name) { mBound = false; scorerService = null; LOG.d("localScorer onServiceDisconnected"); } }; @Override public void start() throws Exception { countDownLatch = new CountDownLatch(1); Intent intent = new Intent(application, ScorerService.class); long startTime = System.currentTimeMillis(); application.bindService(intent, mConnection, Context.BIND_AUTO_CREATE); countDownLatch.await(); LOG.d(String.format("localScorer cost %dms to connect service", System.currentTimeMillis() - startTime)); Bundle bundle = new Bundle(); bundle.putString("spokenText", spokenText); scorerService.init(bundle); scorerService.start(); } @Override public void flow(byte[] bytes, int size) throws Exception { scorerService.flow(bytes, size); } @Override public boolean needExit() { try { return scorerService.needExit(); } catch (RemoteException e) { e.printStackTrace(); return true; } } @Override public void end() throws Exception { scorerService.end(); score = scorerService.getResult().getInt("score"); } @Override public void release() { try { hasRelease = true; if (mBound) { application.unbindService(mConnection); mBound = false; } } catch (Exception ex) { LOG.e(ex); } } public int getScore() { return score; } } ================================================ FILE: demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/RecordPermissionHelper.java ================================================ package com.liulishuo.engzo.lingorecorder.demo; import android.Manifest; import android.content.DialogInterface; import android.content.pm.PackageManager; import android.os.Build; import android.widget.Toast; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.core.content.PermissionChecker; /** * Created by rantianhua on 17/8/29. */ public class RecordPermissionHelper { private static final int REQUEST_CODE_PERMISSION = 10010; private final AppCompatActivity activity; private PermissionGrantedListener grantedListener; public RecordPermissionHelper(AppCompatActivity activity) { this.activity = activity; } public void setGrantedListener( PermissionGrantedListener grantedListener) { this.grantedListener = grantedListener; } public boolean checkRecordPermission() { if (PermissionChecker.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PermissionChecker.PERMISSION_GRANTED || PermissionChecker.checkSelfPermission(activity, Manifest.permission.RECORD_AUDIO) != PermissionChecker.PERMISSION_GRANTED) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (activity.shouldShowRequestPermissionRationale( Manifest.permission.WRITE_EXTERNAL_STORAGE) || activity.shouldShowRequestPermissionRationale( Manifest.permission.RECORD_AUDIO)) { new AlertDialog.Builder(activity) .setTitle(R.string.check_permission_title) .setMessage(R.string.check_permission_content) .setCancelable(false) .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { activity.requestPermissions(new String[]{ Manifest.permission .WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO}, REQUEST_CODE_PERMISSION); } } }).show(); } else { activity.requestPermissions( new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO}, REQUEST_CODE_PERMISSION); } } return false; } return true; } public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { if (requestCode == REQUEST_CODE_PERMISSION) { for (int grantResult : grantResults) { if (grantResult != PackageManager.PERMISSION_GRANTED) { Toast.makeText(activity, R.string.check_permission_fail, Toast.LENGTH_LONG).show(); return; } } if (grantedListener != null) { grantedListener.onPermissionGranted(); } } } public interface PermissionGrantedListener { void onPermissionGranted(); } } ================================================ FILE: demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/ScorerService.java ================================================ package com.liulishuo.engzo.lingorecorder.demo; import android.app.Service; import android.content.Intent; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import androidx.annotation.Nullable; import com.liulishuo.engzo.IAudioProcessorService; import java.util.Random; /** * Created by wcw on 4/10/17. */ public class ScorerService extends Service { private final IAudioProcessorService.Stub mBinder = new IAudioProcessorService.Stub() { private Random random; private Bundle resultBundle; @Override public void init(Bundle bundle) throws RemoteException { resultBundle = new Bundle(); } @Override public void start() throws RemoteException { random = new Random(); } @Override public void flow(byte[] bytes, int result) throws RemoteException { } @Override public boolean needExit() throws RemoteException { return false; } @Override public void end() throws RemoteException { resultBundle.putInt("score", random.nextInt(100)); } @Override public void release() throws RemoteException { random = null; } @Override public Bundle getResult() throws RemoteException { return resultBundle; } }; @Nullable @Override public IBinder onBind(Intent intent) { return mBinder; } } ================================================ FILE: demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/Utils.java ================================================ package com.liulishuo.engzo.lingorecorder.demo; import android.annotation.TargetApi; import android.media.MediaCodecInfo; import android.media.MediaCodecList; import android.os.Build; import java.io.File; import java.text.DecimalFormat; /** * Created by rantianhua on 17/8/29. */ public class Utils { public static String getDurationString(long durationInMills) { if (durationInMills < 1000) { return durationInMills + "ms"; } else if (durationInMills < 1000 * 60) { return (durationInMills / 1000) + "s"; } else { return (durationInMills / 1000) + "min"; } } public static String formatFileSize(String path) { File file = new File(path); long size = file.length(); String[] units = {"B", "kB", "MB", "GB", "TB"}; if (size > 0) { int digitGroups = (int) (Math.log10(size) / Math.log10(1024.0)); return new DecimalFormat("#,##0.#").format(size / Math.pow(1024.0, digitGroups)) + " " + units[digitGroups]; } else { return "0B"; } } public static MediaCodecInfo checkSupportMediaCodec(String mimeType) { if (Build.VERSION.SDK_INT < 16) { // TODO: 17/8/30 get codec list under api 16 https://stackoverflow // .com/questions/19992479/how-to-get-the-codec-list-on-android-4-0 return null; } if (Build.VERSION.SDK_INT < 21) { final int count = MediaCodecList.getCodecCount(); for (int i = 0; i < count; i++) { MediaCodecInfo codecInfo = MediaCodecList.getCodecInfoAt(i); if (!codecInfo.isEncoder()) { continue; } if (checkIsSpecifyCodec(mimeType, codecInfo)) { return codecInfo; } } return null; } else { final MediaCodecList mediaCodecList = new MediaCodecList(MediaCodecList.REGULAR_CODECS); for (MediaCodecInfo codecInfo : mediaCodecList.getCodecInfos()) { if (checkIsSpecifyCodec(mimeType, codecInfo)) { return codecInfo; } } return null; } } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) private static boolean checkIsSpecifyCodec(String mimeType, MediaCodecInfo mediaCodecInfo) { String[] types = mediaCodecInfo.getSupportedTypes(); for (String type : types) { if (type.equalsIgnoreCase(mimeType)) { return true; } } return false; } } ================================================ FILE: demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/activity/AcrossProcessDemonstrateActivity.java ================================================ package com.liulishuo.engzo.lingorecorder.demo.activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.liulishuo.engzo.lingorecorder.LingoRecorder; import com.liulishuo.engzo.lingorecorder.demo.LocalScorerProcessor; import com.liulishuo.engzo.lingorecorder.demo.R; import com.liulishuo.engzo.lingorecorder.processor.AudioProcessor; import java.util.Map; /** * demonstrate across process processor */ public class AcrossProcessDemonstrateActivity extends RecordActivity { public static final String SCORER = "localScorer"; private Button btnScorer; private TextView tvResult; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_across_process_demonstrate); btnScorer = (Button) findViewById(R.id.btn_scorer); tvResult = (TextView) findViewById(R.id.tv_scorer_result); tvResult.setText(getString(R.string.scorer_result, "")); btnScorer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!checkRecordPermission()) return; if (lingoRecorder.isRecording()) { lingoRecorder.stop(); } else if (!lingoRecorder.isProcessing()){ lingoRecorder.start(); tvResult.setText(getString(R.string.scorer_result, "")); btnScorer.setText(R.string.stop_scorer); } } }); final String spokenText = getString(R.string.scorer_sentence); lingoRecorder.put(SCORER, new LocalScorerProcessor(getApplication(), spokenText)); } @Override protected void onProcessError(Throwable throwable) { super.onProcessError(throwable); btnScorer.setText(R.string.start_record); } @Override protected void onRecordError(Throwable throwable) { super.onRecordError(throwable); btnScorer.setText(R.string.start_record); } @Override protected void onProcessStop(Map map) { btnScorer.setText(R.string.start_record); LocalScorerProcessor localScorerProcessor = (LocalScorerProcessor) map.get(SCORER); tvResult.setText( getString(R.string.scorer_result, String.valueOf(localScorerProcessor.getScore()))); } @Override protected void onRecordStop(LingoRecorder.OnRecordStopListener.Result result) { } @Override protected void onPermissionGranted() { btnScorer.performClick(); } } ================================================ FILE: demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/activity/DemoListActivity.java ================================================ package com.liulishuo.engzo.lingorecorder.demo.activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import com.liulishuo.engzo.lingorecorder.demo.R; /** * Created by rantianhua on 17/8/29. * show demo list */ public class DemoListActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_demo_list); } public void recordDemonstrate(View view) { startActivity(new Intent(this, RecordDemonstrateActivity.class)); } public void processorsDemonstrate(View view) { startActivity(new Intent(this, ProcessorsDemonstrateActivity.class)); } public void flacDemonstrate(View view) { startActivity(new Intent(this, FlacDemonstrateActivity.class)); } public void acrossProcessDemonstrate(View view) { startActivity(new Intent(this, AcrossProcessDemonstrateActivity.class)); } public void volumeDemonstrate(View view) { startActivity(new Intent(this, VolumeDemonstrateActivity.class)); } } ================================================ FILE: demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/activity/FlacDemonstrateActivity.java ================================================ package com.liulishuo.engzo.lingorecorder.demo.activity; import android.annotation.TargetApi; import android.os.Build; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.liulishuo.engzo.lingorecorder.LingoRecorder; import com.liulishuo.engzo.lingorecorder.demo.AndroidFlacProcessor; import com.liulishuo.engzo.lingorecorder.demo.R; import com.liulishuo.engzo.lingorecorder.demo.Utils; import com.liulishuo.engzo.lingorecorder.processor.AudioProcessor; import java.util.Map; /** * demonstrate flac codec */ public class FlacDemonstrateActivity extends RecordActivity { private static final String FLAC = "androidFlac"; private Button btnRecord; private EditText etOutput; private TextView tvDuration; private TextView tvSize; private AndroidFlacProcessor flacProcessor; private String outputFile; @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_flac_demonstrate); tvDuration = (TextView) findViewById(R.id.record_duration); tvSize = (TextView) findViewById(R.id.record_size); tvDuration.setText(getString(R.string.record_duration, "")); tvSize.setText(getString(R.string.record_size, "")); etOutput = (EditText) findViewById(R.id.et_output_file); View unSupportView = findViewById(R.id.tv_unsuport_view); View demonstrateView = findViewById(R.id.view_demonstrate); final boolean supportFlac = checkSupportFlac(); if (!supportFlac) { unSupportView.setVisibility(View.VISIBLE); demonstrateView.setVisibility(View.GONE); return; } unSupportView.setVisibility(View.GONE); demonstrateView.setVisibility(View.VISIBLE); flacProcessor = new AndroidFlacProcessor(); lingoRecorder.put(FLAC, flacProcessor); btnRecord = (Button) findViewById(R.id.btn_record); btnRecord.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!checkRecordPermission()) return; if (lingoRecorder.isRecording()) { lingoRecorder.stop(); } else if (!lingoRecorder.isProcessing()){ outputFile = etOutput.getText().toString(); flacProcessor.setFilePath(outputFile); lingoRecorder.start(); btnRecord.setText(R.string.stop_record); } } }); } private boolean checkSupportFlac() { return Utils.checkSupportMediaCodec("audio/flac") != null; } @Override protected void onRecordError(Throwable throwable) { super.onRecordError(throwable); btnRecord.setText(R.string.start_record); } @Override protected void onProcessError(Throwable throwable) { super.onProcessError(throwable); btnRecord.setText(R.string.start_record); } @Override protected void onProcessStop(Map map) { btnRecord.setText(R.string.start_record); tvSize.setText(getString(R.string.record_size, Utils.formatFileSize(outputFile))); } @Override protected void onRecordStop(LingoRecorder.OnRecordStopListener.Result result) { tvDuration.setText(getString(R.string.record_duration, Utils.getDurationString(result.getDurationInMills()))); } @Override protected void onPermissionGranted() { btnRecord.performClick(); } } ================================================ FILE: demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/activity/ProcessorsDemonstrateActivity.java ================================================ package com.liulishuo.engzo.lingorecorder.demo.activity; import android.content.Context; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.liulishuo.engzo.lingorecorder.LingoRecorder; import com.liulishuo.engzo.lingorecorder.demo.R; import com.liulishuo.engzo.lingorecorder.processor.AudioProcessor; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Map; /** * Created by rantianhua on 17/8/29. * demonstrate how to custom processor for record data */ public class ProcessorsDemonstrateActivity extends RecordActivity { private static final String PROCESSOR_1 = "processor1"; private static final String PROCESSOR_2 = "processor2"; private TextView tvProcessor1; private TextView tvProcessor2; private RecyclerView rcv1; private RecyclerView rcv2; private Button btn; private Handler handler; private ProcessorAdapter adapter1; private ProcessorAdapter adapter2; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_processors_demonstrate); tvProcessor1 = (TextView) findViewById(R.id.tv_processor_1_title); tvProcessor2 = (TextView) findViewById(R.id.tv_processor_2_title); tvProcessor1.setText(getString(R.string.processor_1_title, "")); tvProcessor2.setText(getString(R.string.processor_2_title, "")); rcv1 = (RecyclerView) findViewById(R.id.rcv_processor_1); rcv2 = (RecyclerView) findViewById(R.id.rcv_processor_2); adapter1 = new ProcessorAdapter(); adapter2 = new ProcessorAdapter(); rcv1.setLayoutManager(new LinearLayoutManager(this)); rcv1.setHasFixedSize(true); rcv1.setAdapter(adapter1); rcv2.setLayoutManager(new LinearLayoutManager(this)); rcv2.setHasFixedSize(true); rcv2.setAdapter(adapter2); btn = (Button) findViewById(R.id.btn_record); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!checkRecordPermission()) return; if (lingoRecorder.isRecording()) { lingoRecorder.stop(); } else if (!lingoRecorder.isProcessing()){ lingoRecorder.start(); btn.setText(R.string.stop_record); } } }); initHandler(); initLingoRecorder(); } private void initHandler() { handler = new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message msg) { if (isFinishing()) return false; final String data = (String) msg.obj; if (msg.what == 1) { adapter1.addData(data); rcv1.scrollToPosition(adapter1.getItemCount() - 1); } else if (msg.what == 2) { adapter2.addData(data); rcv2.scrollToPosition(adapter2.getItemCount() - 1); } return false; } }); } private void initLingoRecorder() { lingoRecorder.put(PROCESSOR_1, new AudioProcessor() { private int item; @Override public void start() throws Exception { handler.post(new Runnable() { @Override public void run() { tvProcessor1.setText( getString(R.string.processor_1_title, "start")); } }); } @Override public void flow(byte[] bytes, int size) throws Exception { final Message message = handler.obtainMessage(); message.what = 1; message.obj = String.format(Locale.CHINA, "handle flow item, position at %d, size is %d", (++item), size); handler.sendMessage(message); if (item == 1) { handler.post(new Runnable() { @Override public void run() { tvProcessor1.setText( getString(R.string.processor_1_title, "processing...")); } }); } } @Override public boolean needExit() { return false; } @Override public void end() throws Exception { handler.post(new Runnable() { @Override public void run() { tvProcessor1.setText(getString(R.string.processor_1_title, "stop")); } }); } @Override public void release() { item = 0; } }); lingoRecorder.put(PROCESSOR_2, new AudioProcessor() { private int item; @Override public void start() throws Exception { handler.post(new Runnable() { @Override public void run() { tvProcessor2.setText( getString(R.string.processor_2_title, "start")); } }); } @Override public void flow(byte[] bytes, int size) throws Exception { final Message message = handler.obtainMessage(); message.what = 2; message.obj = String.format(Locale.CHINA, "handle flow item, position at %d, size is %d", (++item), size); handler.sendMessage(message); if (item == 1) { handler.post(new Runnable() { @Override public void run() { tvProcessor2.setText( getString(R.string.processor_2_title, "processing...")); } }); } } @Override public boolean needExit() { return false; } @Override public void end() throws Exception { handler.post(new Runnable() { @Override public void run() { tvProcessor2.setText(getString(R.string.processor_2_title, "stop")); } }); } @Override public void release() { item = 0; } }); } @Override protected void onProcessStop(Map map) { btn.setText(R.string.start_record); } @Override protected void onRecordStop(LingoRecorder.OnRecordStopListener.Result result) { } @Override protected void onPermissionGranted() { btn.performClick(); } static class ProcessorAdapter extends RecyclerView.Adapter { private final List data; ProcessorAdapter() { this.data = new ArrayList<>(); } @Override public VH onCreateViewHolder(ViewGroup parent, int viewType) { final TextView textView = new TextView(parent.getContext()); textView.setTextColor(Color.BLACK); textView.setPadding(0, dpToPx(parent.getContext(), 5), 0, dpToPx(parent.getContext(), 5)); textView.setGravity(Gravity.START | Gravity.CENTER_VERTICAL); return new VH(textView); } int dpToPx(Context context, int dp) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources().getDisplayMetrics()); } @Override public void onBindViewHolder(VH holder, int position) { holder.tv.setText(data.get(position)); } @Override public int getItemCount() { return data.size(); } void addData(String item) { if (data.size() > 20) { data.remove(0); } data.add(item); notifyDataSetChanged(); } static class VH extends RecyclerView.ViewHolder { TextView tv; VH(View itemView) { super(itemView); tv = (TextView) itemView; } } } } ================================================ FILE: demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/activity/RecordActivity.java ================================================ package com.liulishuo.engzo.lingorecorder.demo.activity; import android.os.Bundle; import android.util.Log; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import com.liulishuo.engzo.lingorecorder.LingoRecorder; import com.liulishuo.engzo.lingorecorder.demo.R; import com.liulishuo.engzo.lingorecorder.demo.RecordPermissionHelper; import com.liulishuo.engzo.lingorecorder.processor.AudioProcessor; import java.util.Map; /** * Created by rantianhua on 17/8/29. */ public abstract class RecordActivity extends AppCompatActivity { private static final String TAG = "LingoRecorder"; protected RecordPermissionHelper recordPermissionHelper; protected LingoRecorder lingoRecorder; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); recordPermissionHelper = new RecordPermissionHelper(this); recordPermissionHelper.setGrantedListener( new RecordPermissionHelper.PermissionGrantedListener() { @Override public void onPermissionGranted() { RecordActivity.this.onPermissionGranted(); } }); lingoRecorder = new LingoRecorder(); lingoRecorder.setOnRecordStopListener(new LingoRecorder.OnRecordStopListener() { @Override public void onRecordStop(Throwable throwable, Result result) { if (throwable != null) { RecordActivity.this.onRecordError(throwable); } else { RecordActivity.this.onRecordStop(result); } } }); lingoRecorder.setOnProcessStopListener(new LingoRecorder.OnProcessStopListener() { @Override public void onProcessStop(Throwable throwable, Map map) { if (throwable != null) { RecordActivity.this.onProcessError(throwable); } else { RecordActivity.this.onProcessStop(map); } } }); } protected void onProcessError(Throwable throwable) { Toast.makeText(this, getString(R.string.process_failed), Toast.LENGTH_SHORT).show(); Log.e(TAG, "Error in processor: \n" + Log.getStackTraceString(throwable), throwable); } protected void onRecordError(Throwable throwable) { Toast.makeText(this, getString(R.string.record_failed), Toast.LENGTH_SHORT).show(); Log.e(TAG, "Error in recorder: \n" + Log.getStackTraceString(throwable), throwable); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); recordPermissionHelper.onRequestPermissionsResult(requestCode, permissions, grantResults); } protected boolean checkRecordPermission() { return recordPermissionHelper.checkRecordPermission(); } @Override protected void onDestroy() { super.onDestroy(); if (lingoRecorder.isRecording()) { lingoRecorder.cancel(); } } protected abstract void onProcessStop(Map map); protected abstract void onRecordStop(LingoRecorder.OnRecordStopListener.Result result); protected abstract void onPermissionGranted(); } ================================================ FILE: demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/activity/RecordDemonstrateActivity.java ================================================ package com.liulishuo.engzo.lingorecorder.demo.activity; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.core.content.FileProvider; import com.liulishuo.engzo.lingorecorder.LingoRecorder; import com.liulishuo.engzo.lingorecorder.demo.BuildConfig; import com.liulishuo.engzo.lingorecorder.demo.R; import com.liulishuo.engzo.lingorecorder.demo.Utils; import com.liulishuo.engzo.lingorecorder.processor.AudioProcessor; import com.liulishuo.engzo.lingorecorder.volume.OnVolumeListener; import java.io.File; import java.util.Map; /** * Created by rantianhua on 17/8/29. * demonstrate how to record with {@link LingoRecorder} */ public class RecordDemonstrateActivity extends RecordActivity { private Button btnRecord; private Button btnPlay; private TextView tvRecordDuration; private TextView tvRecordSize; private EditText etOutputFile; private String outputFile; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_record_demonstrate); btnRecord = (Button) findViewById(R.id.btn_record); btnPlay = (Button) findViewById(R.id.btn_play); tvRecordDuration = (TextView) findViewById(R.id.record_duration); tvRecordSize = (TextView) findViewById(R.id.record_size); etOutputFile = (EditText) findViewById(R.id.et_output_file); tvRecordDuration.setText(getString(R.string.record_duration, "")); tvRecordSize.setText(getString(R.string.record_size, "")); btnRecord.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!checkRecordPermission()) return; handleRecorderBtn(); } }); btnPlay.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); Uri contentUri = FileProvider.getUriForFile( getApplicationContext(), BuildConfig.APPLICATION_ID + ".fileProvider", new File(outputFile)); intent.setDataAndType(contentUri, "audio/*"); } else { intent.setDataAndType(Uri.parse("file://" + outputFile), "audio/*"); } startActivity(intent); } }); lingoRecorder.setOnVolumeListener(new OnVolumeListener() { @Override public void onVolume(double volume) { Log.d(RecordDemonstrateActivity.class.getSimpleName(), "volume is " + volume); } }); } private void handleRecorderBtn() { if (lingoRecorder.isRecording()) { lingoRecorder.stop(); } else if (!lingoRecorder.isProcessing()) { lingoRecorder.start(etOutputFile.getText().toString()); btnRecord.setText(R.string.stop_record); btnPlay.setEnabled(false); } } @Override protected void onRecordError(Throwable throwable) { super.onRecordError(throwable); btnRecord.setText(R.string.start_record); } @Override protected void onProcessError(Throwable throwable) { super.onProcessError(throwable); btnRecord.setText(R.string.start_record); } @Override protected void onProcessStop(Map map) { btnRecord.setText(R.string.start_record); btnPlay.setEnabled(true); tvRecordSize.setText(getString(R.string.record_size, Utils.formatFileSize(outputFile))); } @Override protected void onRecordStop(LingoRecorder.OnRecordStopListener.Result result) { outputFile = result.getOutputFilePath(); tvRecordDuration.setText(getString(R.string.record_duration, Utils.getDurationString(result.getDurationInMills()))); } @Override protected void onPermissionGranted() { btnRecord.performClick(); } } ================================================ FILE: demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/activity/VolumeDemonstrateActivity.java ================================================ package com.liulishuo.engzo.lingorecorder.demo.activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import androidx.annotation.Nullable; import com.liulishuo.engzo.lingorecorder.LingoRecorder; import com.liulishuo.engzo.lingorecorder.demo.R; import com.liulishuo.engzo.lingorecorder.demo.view.VolumeView; import com.liulishuo.engzo.lingorecorder.processor.AudioProcessor; import com.liulishuo.engzo.lingorecorder.volume.OnVolumeListener; import java.util.Map; /** * Created by rantianhua on 2017/9/26. * demonstrate the volume value during recording */ public class VolumeDemonstrateActivity extends RecordActivity { private Button btnRecord; private VolumeView volumeView; private double maxVolume = 90; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_volume); volumeView = (VolumeView) findViewById(R.id.volume_view); btnRecord = (Button) findViewById(R.id.btn_record); btnRecord.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!checkRecordPermission()) return; handleRecorderBtn(); } }); lingoRecorder.setOnVolumeListener(new OnVolumeListener() { @Override public void onVolume(double volume) { double rate = volume / maxVolume; //more sensitive to volume change Log.d("VolumeDemonstrate", "rate is " + rate); rate = rate * rate * rate; volumeView.setAmplitude(rate); } }); lingoRecorder.setDebugEnable(true); } private void handleRecorderBtn() { if (lingoRecorder.isRecording()) { lingoRecorder.stop(); } else if (!lingoRecorder.isProcessing()){ lingoRecorder.start(); volumeView.startWave(); btnRecord.setText(R.string.stop_record); } } @Override protected void onRecordError(Throwable throwable) { super.onRecordError(throwable); btnRecord.setText(R.string.start_record); } @Override protected void onProcessError(Throwable throwable) { super.onProcessError(throwable); btnRecord.setText(R.string.start_record); } @Override protected void onProcessStop(Map map) { btnRecord.setText(R.string.start_record); } @Override protected void onRecordStop(LingoRecorder.OnRecordStopListener.Result result) { volumeView.stopWave(); } @Override protected void onPermissionGranted() { btnRecord.performClick(); } } ================================================ FILE: demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/view/VolumeView.java ================================================ package com.liulishuo.engzo.lingorecorder.demo.view; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.os.Build; import android.os.Handler; import android.util.AttributeSet; import android.view.View; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import java.util.ArrayList; import java.util.List; /** * Created by rantianhua on 2017/9/27. * show the change of volume */ public class VolumeView extends View { private Path path; private double amplitude; private int step = 3; private Paint paint; private Handler handler; private Runnable waveRunnable; private long startTime; private List xCalculateSamples; private List originX; public VolumeView(Context context) { super(context); init(); } public VolumeView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } public VolumeView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public VolumeView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(); } private void init() { paint = new Paint(); paint.setStrokeWidth(5); paint.setAntiAlias(true); paint.setStyle(Paint.Style.STROKE); paint.setColor(Color.GREEN); path = new Path(); handler = new Handler(); waveRunnable = new Runnable() { @Override public void run() { invalidate(); startWave(); } }; } @Override protected void onDraw(Canvas canvas) { final int width = getWidth(); final int height = getHeight(); path.reset(); if (xCalculateSamples == null) { calculateSample(width); } final int ampl = (int) (amplitude * (height / 2)); final float offset = ((System.currentTimeMillis() - startTime) / 200f) % 2; path.moveTo(originX.get(0), height / 2); for (int i = 0; i < xCalculateSamples.size(); i++) { final float x = originX.get(i); final float y = (float) (0.75 * Math.sin(xCalculateSamples.get(i) * Math.PI - offset * Math.PI) * (4 / (4 + Math.pow(xCalculateSamples.get(i), 2))) * ampl); path.lineTo(x, y + height / 2); } canvas.drawPath(path, paint); } private void calculateSample(int width) { xCalculateSamples = new ArrayList<>(); originX = new ArrayList<>(); for (int i = 0; i <= width; i += step) { xCalculateSamples.add((i / (float) width) * 4 - 2); originX.add(i); } } public void setAmplitude(double amplitude) { this.amplitude = amplitude; } public void startWave() { if (startTime == 0) { startTime = System.currentTimeMillis(); } handler.postDelayed(waveRunnable, 16); } public void stopWave() { handler.removeCallbacks(waveRunnable); setAmplitude(0); invalidate(); } @Override protected void onDetachedFromWindow() { stopWave(); super.onDetachedFromWindow(); } } ================================================ FILE: demo/src/main/res/layout/activity_across_process_demonstrate.xml ================================================