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.
[  ](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<String, AudioProcessor> 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".
}
});
```
效果图:

## 自定义 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();
}
```
效果图:

## 将 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 中提供了相关示例,效果图:

# 在项目中引用
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 <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@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
================================================
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.liulishuo.engzo.lingorecorder.demo">
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".activity.DemoListActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".activity.RecordDemonstrateActivity"
android:screenOrientation="portrait" />
<activity
android:name=".activity.ProcessorsDemonstrateActivity"
android:screenOrientation="portrait" />
<activity
android:name=".activity.FlacDemonstrateActivity"
android:screenOrientation="portrait" />
<activity
android:name=".activity.AcrossProcessDemonstrateActivity"
android:screenOrientation="portrait" />
<activity
android:name=".activity.VolumeDemonstrateActivity"
android:screenOrientation="portrait" />
<service
android:name=".ScorerService"
android:process=":scorer" />
<provider
android:authorities="com.liulishuo.engzo.lingorecorder.demo.fileProvider"
android:name="androidx.core.content.FileProvider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
</application>
</manifest>
================================================
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<String, AudioProcessor> 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<String, AudioProcessor> 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<String, AudioProcessor> 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<ProcessorAdapter.VH> {
private final List<String> 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<String, AudioProcessor> 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<String, AudioProcessor> 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<String, AudioProcessor> 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<String, AudioProcessor> 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<Float> xCalculateSamples;
private List<Integer> 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
================================================
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.liulishuo.engzo.lingorecorder.demo.activity.AcrossProcessDemonstrateActivity"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/please_read"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:layout_marginStart="20dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/scorer_sentence"
android:textColor="@android:color/black"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:layout_marginStart="20dp"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:layout_marginStart="20dp"
android:layout_marginRight="20dp"
android:layout_marginEnd="20dp"
android:textAllCaps="false"
android:text="@string/start_scorer"
android:id="@+id/btn_scorer"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/scorer_result"
android:textColor="@android:color/black"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:layout_marginStart="20dp"
android:id="@+id/tv_scorer_result"
/>
</LinearLayout>
================================================
FILE: demo/src/main/res/layout/activity_demo_list.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_centerVertical="true"
tools:ignore="UselessParent">
<Button
android:layout_width="200dp"
android:layout_height="45dp"
android:text="@string/record_demonstrate"
android:textAllCaps="false"
android:onClick="recordDemonstrate"
android:layout_gravity="center_horizontal"/>
<Button
android:layout_width="200dp"
android:layout_height="45dp"
android:text="@string/custom_processors_demonstrate"
android:textAllCaps="false"
android:layout_gravity="center_horizontal"
android:onClick="processorsDemonstrate"
android:layout_marginTop="20dp"/>
<Button
android:layout_width="200dp"
android:layout_height="45dp"
android:text="@string/flac_demonstrate"
android:textAllCaps="false"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:onClick="flacDemonstrate"/>
<Button
android:layout_width="200dp"
android:layout_height="45dp"
android:text="@string/across_process_processor_demonstrate"
android:textAllCaps="false"
android:id="@+id/btn_flac_sample"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:onClick="acrossProcessDemonstrate"/>
<Button
android:layout_width="200dp"
android:layout_height="45dp"
android:text="@string/volume_demonstrate"
android:textAllCaps="false"
android:id="@+id/btn_volume_sample"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:onClick="volumeDemonstrate" />
</LinearLayout>
</RelativeLayout>
================================================
FILE: demo/src/main/res/layout/activity_flac_demonstrate.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.liulishuo.engzo.lingorecorder.demo.activity.FlacDemonstrateActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/tv_unsuport_view"
android:text="@string/flac_unsupport"
android:gravity="center"
android:textColor="@android:color/black"
tools:visibility="gone"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/view_demonstrate"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/record_output_address"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:layout_marginStart="20dp"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/et_output_file"
android:inputType="text"
android:textColor="@android:color/black"
android:text="@string/sdcard_test_flac"
android:layout_marginLeft="20dp"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:layout_marginStart="20dp"
android:layout_marginRight="20dp"
android:layout_marginEnd="20dp"
android:textAllCaps="false"
android:text="@string/start_record"
android:id="@+id/btn_record"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="@string/record_duration"
android:textColor="@android:color/black"
android:id="@+id/record_duration"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="@string/record_size"
android:textColor="@android:color/black"
android:id="@+id/record_size"
/>
</LinearLayout>
</LinearLayout>
================================================
FILE: demo/src/main/res/layout/activity_processors_demonstrate.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:paddingTop="10dp"
android:orientation="vertical"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tv_processor_1_title"
android:text="@string/processor_1_title"
android:textColor="@color/colorAccent"/>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:id="@+id/rcv_processor_1"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:paddingTop="10dp"
android:orientation="vertical"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tv_processor_2_title"
android:text="@string/processor_1_title"
android:textColor="@color/colorAccent"/>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:id="@+id/rcv_processor_2"/>
</LinearLayout>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btn_record"
android:textAllCaps="false"
android:text="@string/start_record"/>
</LinearLayout>
================================================
FILE: demo/src/main/res/layout/activity_record_demonstrate.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:orientation="vertical"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/record_output_address"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/et_output_file"
android:inputType="text"
android:textColor="@android:color/black"
android:text="@string/sdcard_test_wav"
android:layout_marginTop="10dp"/>
</LinearLayout>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginStart="20dp"
android:layout_marginRight="20dp"
android:layout_marginEnd="20dp"
android:textAllCaps="false"
android:text="@string/start_record"
android:id="@+id/btn_record"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="@string/record_duration"
android:textColor="@android:color/black"
android:id="@+id/record_duration"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="@string/record_size"
android:textColor="@android:color/black"
android:id="@+id/record_size"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginStart="20dp"
android:layout_marginRight="20dp"
android:layout_marginEnd="20dp"
android:textAllCaps="false"
android:text="@string/play_record"
android:id="@+id/btn_play"
android:enabled="false"
/>
</LinearLayout>
================================================
FILE: demo/src/main/res/layout/activity_volume.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginStart="20dp"
android:layout_marginRight="20dp"
android:layout_marginEnd="20dp"
android:layout_marginTop="20dp"
android:textAllCaps="false"
android:text="@string/start_record"
android:id="@+id/btn_record" />
<com.liulishuo.engzo.lingorecorder.demo.view.VolumeView
android:layout_width="match_parent"
android:layout_height="100dp"
android:id="@+id/volume_view" />
</LinearLayout>
================================================
FILE: demo/src/main/res/values/colors.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
</resources>
================================================
FILE: demo/src/main/res/values/strings.xml
================================================
<resources>
<string name="app_name">LingoRecorder</string>
<string name="check_permission_title">Permission check</string>
<string name="check_permission_content">Need to provide recording and storage permissions.
</string>
<string name="check_permission_fail">Permission fetch failed</string>
<string name="confirm">OK</string>
<string name="record_demonstrate">录音演示</string>
<string name="start_record">Start Record</string>
<string name="record_duration">录音时长:%s</string>
<string name="record_output_address">录音文件输出地址:</string>
<string name="sdcard_test_wav">/sdcard/test.wav</string>
<string name="play_record">Play Record</string>
<string name="stop_record">Stop Record</string>
<string name="record_failed">录音出错</string>
<string name="process_failed">处理录音出错</string>
<string name="record_size">文件大小:%s</string>
<string name="start_scorer">开始打分</string>
<string name="custom_processors_demonstrate">自定义处理器演示</string>
<string name="flac_demonstrate">硬编码 Flac 演示</string>
<string name="across_process_processor_demonstrate">跨进程处理器演示</string>
<string name="processor_1_title">Processor 1 : %s</string>
<string name="processor_2_title">Processor 2 : %s</string>
<string name="flac_unsupport">抱歉, 该机型不支持 Flac 编码器</string>
<string name="sdcard_test_flac">/sdcard/test.flac</string>
<string name="please_read">请读:</string>
<string name="scorer_sentence">I will study english very hard.</string>
<string name="scorer_result">打分结果:%s</string>
<string name="stop_scorer">结束打分</string>
<string name="volume_demonstrate">音量演示</string>
</resources>
================================================
FILE: demo/src/main/res/values/styles.xml
================================================
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</resources>
================================================
FILE: demo/src/test/java/com/liulishuo/engzo/lingorecorder/ExampleUnitTest.java
================================================
package com.liulishuo.engzo.lingorecorder;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
================================================
FILE: gradle/bintray.gradle
================================================
/*
* Copyright (c) 2018 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.
*/
apply plugin: 'com.jfrog.bintray'
afterEvaluate { project ->
task sourcesJar(type: Jar) {
from android.sourceSets.main.java.srcDirs
classifier = 'sources'
}
task javadoc(type: Javadoc) {
failOnError false
source = android.sourceSets.main.java.srcDirs
options {
charSet = 'UTF-8'
links "http://docs.oracle.com/javase/7/docs/api/"
linksOffline "http://d.android.com/reference", System.getenv("ANDROID_HOME") + "/docs/reference"
}
classpath += project.android.libraryVariants.toList().first().javaCompile.classpath
classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
}
task javadocJar(type: Jar, dependsOn: javadoc) {
classifier = 'javadoc'
from javadoc.destinationDir
}
artifacts {
archives javadocJar
archives sourcesJar
}
}
def getBintrayUser() {
return hasProperty('BINTRAY_USER') ? BINTRAY_USER : ""
}
def getBintrayGPGPassword() {
return hasProperty('BINTRAY_GPG_PASSWORD') ? BINTRAY_GPG_PASSWORD : ""
}
def getBintrayApiKey() {
return hasProperty('BINTRAY_API_KEY') ? BINTRAY_API_KEY : ""
}
def getSonatypeUsername() {
return hasProperty('SONATYPE_NEXUS_USERNAME') ? SONATYPE_NEXUS_USERNAME : ""
}
def getSonatypePassword() {
return hasProperty('SONATYPE_NEXUS_PASSWORD') ? SONATYPE_NEXUS_PASSWORD : ""
}
version = VERSION_NAME
bintray {
user = getBintrayUser()
key = getBintrayApiKey()
// publish = true //[Default: false] Whether version should be auto published after an upload
// override = false //[Default: false] Whether to override version artifacts already published
configurations = ['archives']
pkg {
repo = "maven"
name = POM_NAME
desc = POM_DESCRIPTION
websiteUrl = POM_URL
issueTrackerUrl = ISSUE_URL
vcsUrl = POM_SCM_URL
licenses = ["Apache-2.0"]
publish = true
publicDownloadNumbers = true
githubRepo = POM_URL
githubReleaseNotesFile = 'README.md'
version {
gpg {
sign = true //Determines whether to GPG sign the files. The default is false
passphrase = getBintrayGPGPassword()
}
mavenCentralSync {
sync = true
user = getSonatypeUsername()
password = getSonatypePassword()
close = '1' //Optional property. By default the staging repository is closed and artifacts are released to Maven Central. You can optionally turn this behaviour off (by puting 0 as value) and release the version manually.
}
}
}
}
================================================
FILE: gradle/mvn-local.gradle
================================================
/*
* Copyright (c) 2018 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.
*/
apply plugin: 'maven-publish'
task sourceJar(type: Jar) {
from android.sourceSets.main.java.srcDirs
classifier "source"
}
publishing {
publications {
lingoRecorder(MavenPublication) {
groupId GROUP
artifactId POM_ARTIFACT_ID
version VERSION_NAME
artifact(sourceJar)
artifact("$buildDir/outputs/aar/${project.name}-release.aar")
pom.withXml {
def dependenciesNode = asNode().appendNode('dependencies')
configurations.compile.allDependencies.each {
if (it.group != null
&& (it.name != null || "unspecified" == it.name)
&& it.version != null) {
def dependencyNode = dependenciesNode.appendNode('dependency')
dependencyNode.appendNode('groupId', it.group)
dependencyNode.appendNode('artifactId', it.name)
dependencyNode.appendNode('version', it.version)
}
}
}
}
}
}
================================================
FILE: gradle/mvn-push.gradle
================================================
/*
* Copyright 2013 Chris Banes
*
* 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.
*/
apply plugin: 'maven'
apply plugin: 'signing'
apply from: '../gradle/mvn-local.gradle'
apply from: '../gradle/bintray.gradle'
version = VERSION_NAME
group = GROUP
def isReleaseBuild() {
return VERSION_NAME.contains("SNAPSHOT") == false
}
def getReleaseRepositoryUrl() {
return hasProperty('RELEASE_REPOSITORY_URL') ? RELEASE_REPOSITORY_URL :
"https://oss.sonatype.org/service/local/staging/deploy/maven2/"
}
def getSnapshotRepositoryUrl() {
return hasProperty('SNAPSHOT_REPOSITORY_URL') ? SNAPSHOT_REPOSITORY_URL :
"https://oss.sonatype.org/content/repositories/snapshots/"
}
def getRepositoryUsername() {
return hasProperty('SONATYPE_NEXUS_USERNAME') ? SONATYPE_NEXUS_USERNAME : ""
}
def getRepositoryPassword() {
return hasProperty('SONATYPE_NEXUS_PASSWORD') ? SONATYPE_NEXUS_PASSWORD : ""
}
afterEvaluate { project ->
uploadArchives {
repositories {
mavenDeployer {
beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }
pom.groupId = GROUP
pom.artifactId = POM_ARTIFACT_ID
pom.version = VERSION_NAME
repository(url: getReleaseRepositoryUrl()) {
authentication(userName: getRepositoryUsername(), password: getRepositoryPassword())
}
snapshotRepository(url: getSnapshotRepositoryUrl()) {
authentication(userName: getRepositoryUsername(), password: getRepositoryPassword())
}
pom.project {
name POM_NAME
packaging POM_PACKAGING
description POM_DESCRIPTION
url POM_URL
scm {
url POM_SCM_URL
connection POM_SCM_CONNECTION
developerConnection POM_SCM_DEV_CONNECTION
}
licenses {
license {
name POM_LICENCE_NAME
url POM_LICENCE_URL
distribution POM_LICENCE_DIST
}
}
developers {
developer {
id POM_DEVELOPER_ID
name POM_DEVELOPER_NAME
}
}
}
}
}
}
signing {
required { isReleaseBuild() && gradle.taskGraph.hasTask("uploadArchives") }
sign configurations.archives
}
if (project.getPlugins().hasPlugin('com.android.application') ||
project.getPlugins().hasPlugin('com.android.library')) {
task install(type: Upload, dependsOn: assemble) {
repositories.mavenInstaller {
configuration = configurations.archives
pom.groupId = GROUP
pom.artifactId = POM_ARTIFACT_ID
pom.version = VERSION_NAME
pom.project {
name POM_NAME
packaging POM_PACKAGING
description POM_DESCRIPTION
url POM_URL
scm {
url POM_SCM_URL
connection POM_SCM_CONNECTION
developerConnection POM_SCM_DEV_CONNECTION
}
licenses {
license {
name POM_LICENCE_NAME
url POM_LICENCE_URL
distribution POM_LICENCE_DIST
}
}
developers {
developer {
id POM_DEVELOPER_ID
name POM_DEVELOPER_NAME
}
}
}
}
}
task androidJavadocs(type: Javadoc) {
source = android.sourceSets.main.java.source
classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
}
task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) {
classifier = 'javadoc'
from androidJavadocs.destinationDir
}
task androidSourcesJar(type: Jar) {
classifier = 'sources'
from android.sourceSets.main.java.source
}
} else {
install {
repositories.mavenInstaller {
pom.groupId = GROUP
pom.artifactId = POM_ARTIFACT_ID
pom.version = VERSION_NAME
pom.project {
name POM_NAME
packaging POM_PACKAGING
description POM_DESCRIPTION
url POM_URL
scm {
url POM_SCM_URL
connection POM_SCM_CONNECTION
developerConnection POM_SCM_DEV_CONNECTION
}
licenses {
license {
name POM_LICENCE_NAME
url POM_LICENCE_URL
distribution POM_LICENCE_DIST
}
}
developers {
developer {
id POM_DEVELOPER_ID
name POM_DEVELOPER_NAME
}
}
}
}
}
task sourcesJar(type: Jar, dependsOn: classes) {
classifier = 'sources'
from sourceSets.main.allSource
}
task javadocJar(type: Jar, dependsOn: javadoc) {
classifier = 'javadoc'
from javadoc.destinationDir
}
}
if (JavaVersion.current().isJava8Compatible()) {
allprojects {
tasks.withType(Javadoc) {
options.addStringOption('Xdoclint:none', '-quiet')
}
}
}
artifacts {
if (project.getPlugins().hasPlugin('com.android.application') ||
project.getPlugins().hasPlugin('com.android.library')) {
archives androidSourcesJar
archives androidJavadocsJar
} else {
archives sourcesJar
archives javadocJar
}
}
}
================================================
FILE: gradle/wrapper/gradle-wrapper.properties
================================================
#Mon Jul 31 15:15:58 CST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.5.1-all.zip
================================================
FILE: gradle.properties
================================================
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
VERSION_NAME=1.2.5
GROUP=com.liulishuo.engzo
POM_URL=https://github.com/lingochamp/LingoRecorder
ISSUE_URL=https://github.com/lingochamp/LingoRecorder/issues
POM_SCM_URL=https://github.com/lingochamp/LingoRecorder
POM_SCM_CONNECTION=scm:git@github.com:lingochamp/LingoRecorder.git
POM_SCM_DEV_CONNECTION=scm:git@github.com:lingochamp/LingoRecorder.git
POM_LICENCE_NAME=The Apache Software License, Version 2.0
POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt
POM_LICENCE_DIST=repo
POM_DEVELOPER_ID=lingochamp
POM_DEVELOPER_NAME=LingoChamp Inc.
android.useAndroidX=true
android.enableJetifier=true
android.debug.obsoleteApi=true
================================================
FILE: gradlew
================================================
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
================================================
FILE: gradlew.bat
================================================
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
================================================
FILE: library/build.gradle
================================================
apply plugin: 'com.android.library'
android {
compileSdkVersion 28
defaultConfig {
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'
})
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test:rules:1.2.0'
androidTestImplementation 'org.hamcrest:hamcrest-library:1.3'
testImplementation 'junit:junit:4.12'
implementation 'androidx.annotation:annotation:1.1.0'
}
apply from: rootProject.file('gradle/mvn-push.gradle')
================================================
FILE: library/gradle.properties
================================================
POM_ARTIFACT_ID=lingo-recorder
POM_NAME=LingoRecorder
POM_DESCRIPTION=LingoRecord is a better recorder for Android, you can easily process pcm data from it
POM_PACKAGING=aar
================================================
FILE: library/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 *;
#}
================================================
FILE: library/src/androidTest/AndroidManifest.xml
================================================
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.liulishuo.engzo.lingorecorder">
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application android:allowBackup="true"
android:supportsRtl="true">
</application>
</manifest>
================================================
FILE: library/src/androidTest/java/com/liulishuo/engzo/lingorecorder/CancelRecordTest.java
================================================
package com.liulishuo.engzo.lingorecorder;
import android.Manifest;
import android.util.Log;
import androidx.test.filters.SmallTest;
import androidx.test.rule.GrantPermissionRule;
import androidx.test.runner.AndroidJUnit4;
import com.liulishuo.engzo.lingorecorder.processor.AudioProcessor;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
/**
* Created by wcw on 8/9/17.
*/
@RunWith(AndroidJUnit4.class)
@SmallTest
public class CancelRecordTest {
@Rule
public GrantPermissionRule pr = GrantPermissionRule.grant(
Manifest.permission.RECORD_AUDIO,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
private LingoRecorder lingoRecorder;
@Before
public void before() {
lingoRecorder = new LingoRecorder();
}
@Test
public void testCancelRecorderWhenProcessingBlock() {
lingoRecorder.put("blockProcessing", new AudioProcessor() {
private void block(long time) throws InterruptedException {
Thread.sleep(time);
}
@Override
public void start() throws Exception {
block(100000);
}
@Override
public void flow(byte[] bytes, int size) throws Exception {
block(100000);
}
@Override
public boolean needExit() {
return false;
}
@Override
public void end() throws Exception {
block(100000);
}
@Override
public void release() {
}
});
final CountDownLatch countDownLatch = new CountDownLatch(2);
final Throwable[] throwableArray = new Throwable[2];
lingoRecorder.setOnProcessStopListener(new LingoRecorder.OnProcessStopListener() {
@Override
public void onProcessStop(Throwable throwable, Map<String, AudioProcessor> map) {
throwableArray[1] = throwable;
countDownLatch.countDown();
}
});
lingoRecorder.setOnRecordStopListener(new LingoRecorder.OnRecordStopListener() {
@Override
public void onRecordStop(Throwable throwable, Result result) {
throwableArray[0] = throwable;
countDownLatch.countDown();
}
});
lingoRecorder.start();
try {
Thread.sleep(5000);
} catch (InterruptedException ignore) {
}
lingoRecorder.cancel();
long startCancelTime = System.currentTimeMillis();
try {
countDownLatch.await();
} catch (InterruptedException ignore) {
}
long cancelCostTime = System.currentTimeMillis() - startCancelTime;
Assert.assertTrue(cancelCostTime < 1000);
Assert.assertNull(throwableArray[0]);
Assert.assertNotNull(throwableArray[1]);
Log.e(CancelRecordTest.class.getSimpleName(), Log.getStackTraceString(throwableArray[1]));
Assert.assertEquals(LingoRecorder.CancelProcessingException.class, throwableArray[1].getClass());
}
}
================================================
FILE: library/src/androidTest/java/com/liulishuo/engzo/lingorecorder/LingoRecorderTest.java
================================================
package com.liulishuo.engzo.lingorecorder;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
import com.liulishuo.engzo.lingorecorder.processor.AudioProcessor;
import com.liulishuo.engzo.lingorecorder.processor.TimerProcessor;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.File;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
* Created by wcw on 8/9/17.
*/
@RunWith(AndroidJUnit4.class)
@SmallTest
public class LingoRecorderTest {
private LingoRecorder lingoRecorder;
@Before
public void before() {
lingoRecorder = new LingoRecorder();
}
@Test
public void testRecorderStopWhenProcessorThrowException() {
lingoRecorder.put("exception", new AudioProcessor() {
@Override
public void start() throws Exception {
}
@Override
public void flow(byte[] bytes, int size) throws Exception {
throw new RuntimeException("exception");
}
@Override
public boolean needExit() {
return false;
}
@Override
public void end() throws Exception {
}
@Override
public void release() {
}
});
lingoRecorder.put("timer", new TimerProcessor(lingoRecorder.getRecorderProperty(), 1000));
final CountDownLatch countDownLatch = new CountDownLatch(2);
final boolean[] status = new boolean[1];
lingoRecorder.setOnRecordStopListener(new LingoRecorder.OnRecordStopListener() {
@Override
public void onRecordStop(Throwable throwable, Result result) {
countDownLatch.countDown();
status[0] = true;
}
});
lingoRecorder.setOnProcessStopListener(new LingoRecorder.OnProcessStopListener() {
@Override
public void onProcessStop(Throwable throwable, Map<String, AudioProcessor> map) {
countDownLatch.countDown();
}
});
lingoRecorder.start();
try {
countDownLatch.await(2000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
Assert.assertTrue(status[0]);
}
private long getFileSize(String file) {
return new File(file).length();
}
}
================================================
FILE: library/src/androidTest/java/com/liulishuo/engzo/lingorecorder/RecordAndProcessorEndTest.java
================================================
package com.liulishuo.engzo.lingorecorder;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
import com.liulishuo.engzo.lingorecorder.processor.AudioProcessor;
import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
/**
* Created by rantianhua on 17/7/31.
* this class will test the end callback of record and processor
* will be invoked at a fixed order. (recorder end callback always first)
*/
@RunWith(AndroidJUnit4.class)
@SmallTest
public class RecordAndProcessorEndTest {
private AudioProcessor testProcessor;
private LingoRecorder lingoRecorder;
private long recorderEnd;
private long processorEnd;
@Before
public void before() {
lingoRecorder = new LingoRecorder();
}
@Test
public void recorderEndFirstRecorderCallbackFirst() throws Exception {
testProcessor = new AudioProcessor() {
@Override
public void start() throws Exception {
}
@Override
public void flow(byte[] bytes, int size) throws Exception {
}
@Override
public boolean needExit() {
return false;
}
@Override
public void end() throws Exception {
}
@Override
public void release() {
}
};
lingoRecorder.put("test1", testProcessor);
final CountDownLatch countDownLatch = new CountDownLatch(2);
lingoRecorder.setOnRecordStopListener(new LingoRecorder.OnRecordStopListener() {
@Override
public void onRecordStop(Throwable throwable,
Result result) {
recorderEnd = System.nanoTime();
countDownLatch.countDown();
}
});
lingoRecorder.setOnProcessStopListener(new LingoRecorder.OnProcessStopListener() {
@Override
public void onProcessStop(Throwable throwable, Map<String, AudioProcessor> map) {
processorEnd = System.nanoTime();
countDownLatch.countDown();
}
});
lingoRecorder.start();
sleep();
lingoRecorder.stop();
countDownLatch.await();
Assert.assertTrue("OnProcessStopListener must callback after OnRecordStopListener",
processorEnd > recorderEnd);
}
private void sleep() {
try {
Thread.sleep(1000);
} catch (Exception ignore) {
}
}
private String processorErrorMsg = null;
@Test
public void processorMayEndFirstRecorderCallbackFirst() throws Exception {
final String errorMsg = "hah";
testProcessor = new AudioProcessor() {
@Override
public void start() throws Exception {
throw new RuntimeException(errorMsg);
}
@Override
public void flow(byte[] bytes, int size) throws Exception {
}
@Override
public boolean needExit() {
return false;
}
@Override
public void end() throws Exception {
}
@Override
public void release() {
}
};
lingoRecorder.put("test2", testProcessor);
final CountDownLatch countDownLatch = new CountDownLatch(2);
lingoRecorder.setOnRecordStopListener(new LingoRecorder.OnRecordStopListener() {
@Override
public void onRecordStop(Throwable throwable,
Result result) {
recorderEnd = System.nanoTime();
countDownLatch.countDown();
}
});
lingoRecorder.setOnProcessStopListener(new LingoRecorder.OnProcessStopListener() {
@Override
public void onProcessStop(Throwable throwable, Map<String, AudioProcessor> map) {
processorErrorMsg = throwable.getMessage();
processorEnd = System.nanoTime();
countDownLatch.countDown();
}
});
lingoRecorder.start();
sleep();
lingoRecorder.stop();
countDownLatch.await();
Assert.assertTrue("OnProcessStopListener must callback after OnRecordStopListener",
processorEnd > recorderEnd);
Assert.assertThat("processor exception should be obtained by OnProcessStopListener",
processorErrorMsg,
CoreMatchers.is(errorMsg));
}
}
================================================
FILE: library/src/main/AndroidManifest.xml
================================================
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.liulishuo.engzo.lingorecorder">
<application android:allowBackup="true"
android:supportsRtl="true">
</application>
</manifest>
================================================
FILE: library/src/main/aidl/com/liulishuo/engzo/IAudioProcessorService.aidl
================================================
package com.liulishuo.engzo;
interface IAudioProcessorService {
void init(in Bundle bundle);
void start();
void flow(in byte[] bytes, int result);
boolean needExit();
void end();
void release();
Bundle getResult();
}
================================================
FILE: library/src/main/java/com/liulishuo/engzo/lingorecorder/LingoRecorder.java
================================================
package com.liulishuo.engzo.lingorecorder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import androidx.annotation.NonNull;
import com.liulishuo.engzo.lingorecorder.processor.AudioProcessor;
import com.liulishuo.engzo.lingorecorder.processor.WavProcessor;
import com.liulishuo.engzo.lingorecorder.recorder.AndroidRecorder;
import com.liulishuo.engzo.lingorecorder.recorder.IRecorder;
import com.liulishuo.engzo.lingorecorder.recorder.WavFileRecorder;
import com.liulishuo.engzo.lingorecorder.utils.LOG;
import com.liulishuo.engzo.lingorecorder.utils.RecorderProperty;
import com.liulishuo.engzo.lingorecorder.utils.WrapBuffer;
import com.liulishuo.engzo.lingorecorder.volume.DefaultVolumeCalculator;
import com.liulishuo.engzo.lingorecorder.volume.IVolumeCalculator;
import com.liulishuo.engzo.lingorecorder.volume.OnVolumeListener;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
/**
* Created by wcw on 3/28/17.
*/
public class LingoRecorder {
private Map<String, AudioProcessor> audioProcessorMap = new HashMap<>();
private InternalRecorder internalRecorder;
private final static int MESSAGE_RECORD_STOP = 1;
private final static int MESSAGE_PROCESS_STOP = 2;
private final static int MESSAGE_VOLUME = 4;
private final static String KEY_DURATION = "duration";
private final static String KEY_FILEPATH = "filePath";
private OnRecordStopListener onRecordStopListener;
private OnProcessStopListener onProcessStopListener;
private OnVolumeListener onVolumeListener;
private IVolumeCalculator volumeCalculator;
private boolean available = true;
private boolean isProcessing = false;
private final RecorderProperty recorderProperty;
private String wavFilePath;
public LingoRecorder() {
this.recorderProperty = new RecorderProperty();
}
public boolean isProcessing() {
return isProcessing;
}
/**
*
* @deprecated use {@link #isProcessing()} instead
*/
@Deprecated
public boolean isAvailable() {
return available;
}
public boolean isRecording() {
return internalRecorder != null;
}
public boolean start() {
return start(null);
}
public boolean start(String outputFilePath) {
if (internalRecorder != null || isProcessing) {
if (internalRecorder != null) {
LOG.e("start fail recorder is recording");
} else {
LOG.e("start fail recorder is processing");
}
return false;
}
LOG.d("start record");
IRecorder recorder = null;
if (wavFilePath != null) {
recorder = new WavFileRecorder(wavFilePath, recorderProperty);
// wavFileRecorder not support stop
// LingoRecorder will be available until process finish
available = false;
} else {
recorder = new AndroidRecorder(recorderProperty);
}
// clone audioProcessorMap and skip null processor
Map<String, AudioProcessor> immutableMap = new HashMap<>(audioProcessorMap.size());
for (String key : audioProcessorMap.keySet()) {
AudioProcessor audioProcessor = audioProcessorMap.get(key);
if (audioProcessor != null) {
immutableMap.put(key, audioProcessor);
}
}
internalRecorder = new InternalRecorder(recorder, outputFilePath, immutableMap.values(),
new RecorderHandler(this, immutableMap),
volumeCalculator);
isProcessing = true;
internalRecorder.start();
return true;
}
public void stop() {
if (internalRecorder != null) {
LOG.d("end record");
available = false;
LOG.d("record unavailable now");
internalRecorder.stop();
internalRecorder = null;
}
}
public void cancel() {
if (internalRecorder != null) {
available = false;
internalRecorder.cancel();
internalRecorder = null;
}
}
public void setOnRecordStopListener(OnRecordStopListener onRecordStopListener) {
this.onRecordStopListener = onRecordStopListener;
}
public void setOnProcessStopListener(OnProcessStopListener onProcessStopListener) {
this.onProcessStopListener = onProcessStopListener;
}
public void setOnVolumeListener(OnVolumeListener onVolumeListener) {
setOnVolumeListener(onVolumeListener, new DefaultVolumeCalculator());
}
public void setOnVolumeListener(OnVolumeListener onVolumeListener, IVolumeCalculator volumeCalculator) {
this.onVolumeListener = onVolumeListener;
this.volumeCalculator = volumeCalculator;
}
public void put(String processorId, AudioProcessor processor) {
audioProcessorMap.put(processorId, processor);
}
public AudioProcessor remove(String processorId) {
return audioProcessorMap.remove(processorId);
}
public interface OnRecordStopListener {
class Result {
private long durationInMills;
private String outputFilePath;
public long getDurationInMills() {
return durationInMills;
}
public String getOutputFilePath() {
return outputFilePath;
}
}
void onRecordStop(Throwable throwable, Result result);
}
public interface OnProcessStopListener {
void onProcessStop(Throwable throwable, Map<String, AudioProcessor> map);
}
public LingoRecorder sampleRate(int sampleRate) {
recorderProperty.setSampleRate(sampleRate);
return this;
}
public LingoRecorder channels(int channels) {
recorderProperty.setChannels(channels);
return this;
}
public LingoRecorder bitsPerSample(int bitsPerSample) {
recorderProperty.setBitsPerSample(bitsPerSample);
return this;
}
public RecorderProperty getRecorderProperty() {
return recorderProperty;
}
public LingoRecorder wavFile(String filePath) {
this.wavFilePath = filePath;
return this;
}
private static class InternalRecorder implements Runnable {
private volatile boolean shouldRun;
private volatile boolean cancel;
private volatile Throwable processorsError;
private Thread thread;
private IRecorder recorder;
private Collection<AudioProcessor> audioProcessors;
private Handler handler;
private String outputFilePath;
private IVolumeCalculator volumeCalculator;
InternalRecorder(
IRecorder recorder,
String outputFilePath,
Collection<AudioProcessor> audioProcessors,
Handler handler,
IVolumeCalculator volumeCalculator) {
thread = new Thread(this);
this.audioProcessors = audioProcessors;
this.handler = handler;
this.recorder = recorder;
this.outputFilePath = outputFilePath;
this.volumeCalculator = volumeCalculator;
}
void cancel() {
shouldRun = false;
cancel = true;
}
void stop() {
shouldRun = false;
}
void start() {
thread.start();
}
@Override
public void run() {
shouldRun = true;
WavProcessor wavProcessor = null;
Throwable recordException = null;
ProcessThread processThread = null;
try {
int buffSize = recorder.getBufferSize();
byte[] bytes = new byte[buffSize];
processThread = new ProcessThread();
processThread.start();
recorder.startRecording();
if (outputFilePath != null) {
wavProcessor = new WavProcessor(outputFilePath, recorder.getRecordProperty());
wavProcessor.start();
}
while (shouldRun) {
int result = recorder.read(bytes, buffSize);
LOG.d("read buffer result = " + result);
if (result > 0) {
if (volumeCalculator != null) {
final long startCalculateTime = System.currentTimeMillis();
final double volume = volumeCalculator.onAudioChunk(bytes,
result, recorder.getRecordProperty().getBitsPerSample());
final long calculateDuration = System.currentTimeMillis() - startCalculateTime;
LOG.d("duration of calculating chunk volume: " + calculateDuration);
handler.sendMessage(handler.obtainMessage(MESSAGE_VOLUME, volume));
}
processThread.process(bytes, result);
if (wavProcessor != null) {
wavProcessor.flow(bytes, result);
}
} else if (result < 0) {
LOG.d("exit read from recorder result = " + result);
shouldRun = false;
break;
}
}
if (wavProcessor != null) {
wavProcessor.end();
}
} catch (Throwable e) {
LOG.e(e);
recordException = e;
} finally {
shouldRun = false;
if (wavProcessor != null) {
wavProcessor.release();
}
recorder.release();
// notify recorder stop
Message message = Message.obtain();
message.what = MESSAGE_RECORD_STOP;
Bundle bundle = new Bundle();
bundle.putLong(KEY_DURATION, recorder.getDurationInMills());
bundle.putString(KEY_FILEPATH, outputFilePath);
message.setData(bundle);
message.obj = recordException;
handler.sendMessage(message);
if (recordException != null) {
cancel = true;
}
// try to end processor thread
if (processThread != null) {
processThread.end(cancel);
}
// notify processor stop
Message msg = Message.obtain();
msg.what = MESSAGE_PROCESS_STOP;
if (recordException != null) {
msg.obj = new RecordErrorCancelProcessingException(processorsError);
} else {
msg.obj = processorsError;
}
handler.sendMessage(msg);
}
}
class ProcessThread extends Thread {
private LinkedBlockingQueue<Object> processorQueue;
ProcessThread() {
this(new LinkedBlockingQueue<>());
}
ProcessThread(final LinkedBlockingQueue<Object> processorQueue) {
super("processThread");
this.processorQueue = processorQueue;
}
void process(@NonNull byte[] bytes, int buffSize) throws InterruptedException {
WrapBuffer wrapBuffer = new WrapBuffer();
wrapBuffer.setBytes(Arrays.copyOf(bytes, bytes.length));
wrapBuffer.setSize(buffSize);
processorQueue.put(wrapBuffer);
}
void end(boolean cancel) {
try {
processorQueue.put("end");
if (cancel) {
interrupt();
}
join();
LOG.d("processorThread end");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void run() {
super.run();
Object value;
try {
for (AudioProcessor audioProcessor : audioProcessors) {
checkIfNeedCancel();
audioProcessor.start();
}
while ((value = processorQueue.take()) != null) {
if (value instanceof WrapBuffer) {
for (AudioProcessor audioProcessor : audioProcessors) {
checkIfNeedCancel();
WrapBuffer wrapBuffer = (WrapBuffer) value;
audioProcessor.flow(wrapBuffer.getBytes(), wrapBuffer.getSize());
}
for (AudioProcessor audioProcessor : audioProcessors) {
checkIfNeedCancel();
if (audioProcessor.needExit()) {
LOG.d(String.format("exit because %s", audioProcessor));
shouldRun = false;
break;
}
}
} else {
break;
}
}
for (AudioProcessor audioProcessor : audioProcessors) {
checkIfNeedCancel();
audioProcessor.end();
}
} catch (InterruptedException e) {
processorsError = new CancelProcessingException(e);
} catch (Throwable e) {
processorsError = e;
LOG.e(e);
} finally {
shouldRun = false;
for (AudioProcessor audioProcessor : audioProcessors) {
audioProcessor.release();
}
}
}
}
private void checkIfNeedCancel() {
if (cancel) {
throw new CancelProcessingException();
}
}
}
private static class RecorderHandler extends Handler {
private LingoRecorder mLingoRecorder;
private Map<String, AudioProcessor> mAudioProcessorMap;
RecorderHandler(LingoRecorder lingoRecorder, Map<String, AudioProcessor> audioProcessorMap) {
super(Looper.getMainLooper());
mLingoRecorder = lingoRecorder;
mAudioProcessorMap = audioProcessorMap;
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case MESSAGE_RECORD_STOP:
mLingoRecorder.internalRecorder = null;
handleRecordStop(msg);
break;
case MESSAGE_PROCESS_STOP:
mLingoRecorder.available = true;
mLingoRecorder.isProcessing = false;
handleProcessStop(msg);
break;
case MESSAGE_VOLUME:
if (mLingoRecorder.onVolumeListener != null) {
mLingoRecorder.onVolumeListener.onVolume((Double) msg.obj);
}
break;
}
}
private void handleRecordStop(Message msg) {
long durationInMills = msg.getData().getLong(KEY_DURATION, -1);
String outputFilePath = msg.getData().getString(KEY_FILEPATH);
if (mLingoRecorder.onRecordStopListener != null) {
OnRecordStopListener.Result result = new OnRecordStopListener.Result();
result.durationInMills = durationInMills;
result.outputFilePath = outputFilePath;
mLingoRecorder.onRecordStopListener.onRecordStop((Throwable) msg.obj, result);
}
LOG.d("record end");
}
private void handleProcessStop(Message msg) {
if (mLingoRecorder.onProcessStopListener != null) {
mLingoRecorder.onProcessStopListener.onProcessStop((Throwable) msg.obj, mAudioProcessorMap);
}
LOG.d("process end");
}
}
public static class CancelProcessingException extends RuntimeException {
public CancelProcessingException() {
super("cancel processing");
}
public CancelProcessingException(Throwable throwable) {
super(throwable);
}
}
public static class RecordErrorCancelProcessingException extends CancelProcessingException {
public RecordErrorCancelProcessingException(Throwable throwable) {
super(throwable);
}
}
public void setDebugEnable(boolean enable) {
LOG.isEnable = enable;
}
}
================================================
FILE: library/src/main/java/com/liulishuo/engzo/lingorecorder/processor/AudioProcessor.java
================================================
package com.liulishuo.engzo.lingorecorder.processor;
/**
* Created by wcw on 3/28/17.
*/
public interface AudioProcessor {
void start() throws Exception;
void flow(byte[] bytes, int size) throws Exception;
boolean needExit();
void end() throws Exception;
void release();
}
================================================
FILE: library/src/main/java/com/liulishuo/engzo/lingorecorder/processor/TimerProcessor.java
================================================
package com.liulishuo.engzo.lingorecorder.processor;
import com.liulishuo.engzo.lingorecorder.utils.RecorderProperty;
public class TimerProcessor implements AudioProcessor {
private long mTimeInMills;
private RecorderProperty mRecorderProperty;
private long payloadSize = 0L;
public TimerProcessor(long timeInMills) {
this(new RecorderProperty(), timeInMills);
}
public TimerProcessor(RecorderProperty recorderProperty, long timeInMills) {
mRecorderProperty = recorderProperty;
mTimeInMills = timeInMills;
}
@Override
public void start() {
payloadSize = 0;
}
@Override
public void flow(byte[] bytes, int size) {
payloadSize += size;
}
@Override
public boolean needExit() {
long payloadSizeInBits = payloadSize * 8;
long durationInMills = (long)
(payloadSizeInBits * 1000.0 / mRecorderProperty.getBitsPerSample()
/ mRecorderProperty.getSampleRate() / mRecorderProperty.getChannels());
return durationInMills >= mTimeInMills;
}
@Override
public void end() {
}
@Override
public void release() {
}
}
================================================
FILE: library/src/main/java/com/liulishuo/engzo/lingorecorder/processor/WavProcessor.java
================================================
package com.liulishuo.engzo.lingorecorder.processor;
import com.liulishuo.engzo.lingorecorder.utils.RecorderProperty;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
/**
* Created by wcw on 3/28/17.
*/
public class WavProcessor implements AudioProcessor {
private String filePath;
private RandomAccessFile writer;
private int payloadSize = 0;
private RecorderProperty recordProperty;
public WavProcessor(String filePath) {
this(filePath, new RecorderProperty());
}
public WavProcessor(String filePath, RecorderProperty recordProperty) {
this.filePath = filePath;
this.recordProperty = recordProperty;
}
@Override
public void start() throws Exception {
payloadSize = 0;
// http://soundfile.sapp.org/doc/WaveFormat/
try {
writer = new RandomAccessFile(filePath, "rw");
} catch (FileNotFoundException ex) {
// Maybe the parent directory doesn't exist? Try creating it first.
new File(filePath).getParentFile().mkdirs();
writer = new RandomAccessFile(filePath, "rw");
}
writer.setLength(0); // Set file length to 0, to prevent unexpected behavior in case the file already existed
writer.writeBytes("RIFF");
writer.writeInt(0); // Final file size not known yet, write 0
writer.writeBytes("WAVE");
writer.writeBytes("fmt ");
writer.writeInt(Integer.reverseBytes(16)); // Sub-chunk size, 16 for PCM
writer.writeShort(Short.reverseBytes((short) 1)); // AudioFormat, 1 for PCM
writer.writeShort(Short.reverseBytes(
(short) recordProperty.getChannels()));// Number of channels, 1 for mono, 2 for
// stereo
writer.writeInt(Integer.reverseBytes(recordProperty.getSampleRate())); // Sample rate
writer.writeInt(Integer.reverseBytes(
recordProperty.getSampleRate() * recordProperty.getChannels()
* recordProperty.getBitsPerSample()
/ 8)); // Byte rate, SampleRate*NumberOfChannels*bitsPerSample/8
writer.writeShort(Short.reverseBytes(
(short) (recordProperty.getChannels() * recordProperty.getBitsPerSample()
/ 8))); // Block align, NumberOfChannels*bitsPerSample/8
writer.writeShort(
Short.reverseBytes((short) recordProperty.getBitsPerSample())); // Bits per sample
writer.writeBytes("data");
writer.writeInt(0); // Data chunk size not known yet, write 0
}
@Override
public void flow(byte[] bytes, int result) throws Exception {
if (result > 0) {
writer.write(bytes);
payloadSize += result;
}
}
@Override
public boolean needExit() {
return false;
}
@Override
public void end() throws Exception {
writer.seek(4); // Write size to RIFF header
writer.writeInt(Integer.reverseBytes(36 + payloadSize));
writer.seek(40); // Write size to Subchunk2Size field
writer.writeInt(Integer.reverseBytes(payloadSize));
}
@Override
public void release() {
try {
if (writer != null) {
writer.close();
writer = null;
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public String getFilePath() {
return filePath;
}
public RecorderProperty getRecordProperty() {
return recordProperty;
}
}
================================================
FILE: library/src/main/java/com/liulishuo/engzo/lingorecorder/recorder/AndroidRecorder.java
================================================
package com.liulishuo.engzo.lingorecorder.recorder;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import androidx.annotation.NonNull;
import com.liulishuo.engzo.lingorecorder.recorder.exception.RecorderException;
import com.liulishuo.engzo.lingorecorder.recorder.exception.RecorderGetBufferSizeException;
import com.liulishuo.engzo.lingorecorder.recorder.exception.RecorderInitException;
import com.liulishuo.engzo.lingorecorder.recorder.exception.RecorderReadException;
import com.liulishuo.engzo.lingorecorder.recorder.exception.RecorderStartException;
import com.liulishuo.engzo.lingorecorder.utils.RecorderProperty;
/**
* Created by wcw on 4/5/17.
*/
public class AndroidRecorder implements IRecorder {
private int audioFormat;
private long payloadSize;
private int channels;
private AudioRecord recorder;
private final RecorderProperty recorderProperty;
public AndroidRecorder(final RecorderProperty recorderProperty) {
this.recorderProperty = recorderProperty;
if (this.recorderProperty.getBitsPerSample() == 16) {
audioFormat = AudioFormat.ENCODING_PCM_16BIT;
} else if (this.recorderProperty.getBitsPerSample() == 8) {
audioFormat = AudioFormat.ENCODING_PCM_8BIT;
} else {
throw new RecorderException(
"unsupported bitsPerSample: " + this.recorderProperty.getBitsPerSample());
}
if (this.recorderProperty.getChannels() == 1) {
this.channels = AudioFormat.CHANNEL_IN_MONO;
} else if (this.recorderProperty.getChannels() == 2) {
this.channels = AudioFormat.CHANNEL_IN_STEREO;
} else {
throw new RecorderException(
"unsupported channel: " + this.recorderProperty.getChannels());
}
}
@Override
public int getBufferSize() {
int ret = AudioRecord.getMinBufferSize(recorderProperty.getSampleRate(), channels,
audioFormat);
if (ret > 0) {
return 2 * ret;
} else {
throw new RecorderGetBufferSizeException(ret);
}
}
@Override
public void startRecording() throws Exception {
int buffSize = getBufferSize();
recorder = new AudioRecord(MediaRecorder.AudioSource.MIC, recorderProperty.getSampleRate(),
channels, audioFormat, buffSize);
if (recorder.getState() != AudioRecord.STATE_INITIALIZED) {
throw new RecorderInitException();
}
payloadSize = 0;
recorder.startRecording();
if (recorder.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING) {
throw new RecorderStartException();
}
}
@Override
public int read(@NonNull byte[] bytes, int buffSize) throws Exception {
int read = recorder.read(bytes, 0, buffSize);
if (read < 0) {
throw new RecorderReadException(read);
}
payloadSize += read;
return read;
}
@Override
public void release() {
if (recorder != null) {
recorder.release();
}
}
@Override
public long getDurationInMills() {
return (long) (payloadSize * 8.0 * 1000 / recorderProperty.getBitsPerSample()
/ recorderProperty.getSampleRate() / recorderProperty.getChannels());
}
@Override
public RecorderProperty getRecordProperty() {
return recorderProperty;
}
}
================================================
FILE: library/src/main/java/com/liulishuo/engzo/lingorecorder/recorder/IRecorder.java
================================================
package com.liulishuo.engzo.lingorecorder.recorder;
import androidx.annotation.NonNull;
import com.liulishuo.engzo.lingorecorder.utils.RecorderProperty;
/**
* Created by wcw on 4/5/17.
*/
public interface IRecorder {
int getBufferSize() throws Throwable;
void startRecording() throws Throwable;
int read(@NonNull byte[] bytes, int buffSize) throws Throwable;
void release();
long getDurationInMills();
RecorderProperty getRecordProperty();
}
================================================
FILE: library/src/main/java/com/liulishuo/engzo/lingorecorder/recorder/WavFileRecorder.java
================================================
package com.liulishuo.engzo.lingorecorder.recorder;
import androidx.annotation.NonNull;
import com.liulishuo.engzo.lingorecorder.utils.LOG;
import com.liulishuo.engzo.lingorecorder.utils.RecorderProperty;
import java.io.FileInputStream;
/**
* Created by wcw on 4/5/17.
*/
public class WavFileRecorder implements IRecorder {
private FileInputStream fis;
private long payloadSize;
private final String filePath;
private final RecorderProperty recorderProperty;
public WavFileRecorder(String filePath, RecorderProperty recorderProperty) {
this.filePath = filePath;
this.recorderProperty = recorderProperty;
}
@Override
public int getBufferSize() {
return 1024;
}
@Override
public void startRecording() throws Exception {
fis = new FileInputStream(filePath);
long skip = fis.skip(44);
LOG.d("skip size = " + skip);
payloadSize = 0;
}
@Override
public int read(@NonNull byte[] bytes, int buffSize) throws Exception {
int count = fis.read(bytes, 0, buffSize);
payloadSize += count;
return count;
}
@Override
public void release() {
try {
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public long getDurationInMills() {
return (long) (payloadSize * 8.0 * 1000 / recorderProperty.getBitsPerSample()
/ recorderProperty.getSampleRate() / recorderProperty.getChannels());
}
@Override
public RecorderProperty getRecordProperty() {
return recorderProperty;
}
}
================================================
FILE: library/src/main/java/com/liulishuo/engzo/lingorecorder/recorder/exception/RecorderException.java
================================================
package com.liulishuo.engzo.lingorecorder.recorder.exception;
/**
* Created by wcw on 1/26/18.
*/
public class RecorderException extends RuntimeException {
public RecorderException(String message) {
super((message));
}
}
================================================
FILE: library/src/main/java/com/liulishuo/engzo/lingorecorder/recorder/exception/RecorderGetBufferSizeException.java
================================================
package com.liulishuo.engzo.lingorecorder.recorder.exception;
/**
* Created by wcw on 1/26/18.
*/
public class RecorderGetBufferSizeException extends RecorderException {
public RecorderGetBufferSizeException(int error) {
super("recorder get buffer size error " + error);
}
}
================================================
FILE: library/src/main/java/com/liulishuo/engzo/lingorecorder/recorder/exception/RecorderInitException.java
================================================
package com.liulishuo.engzo.lingorecorder.recorder.exception;
/**
* Created by wcw on 1/26/18.
*/
public class RecorderInitException extends RecorderException {
public RecorderInitException() {
super("init Android audioRecorder error");
}
}
================================================
FILE: library/src/main/java/com/liulishuo/engzo/lingorecorder/recorder/exception/RecorderReadException.java
================================================
package com.liulishuo.engzo.lingorecorder.recorder.exception;
/**
* Created by wcw on 1/26/18.
*/
public class RecorderReadException extends RecorderException {
public RecorderReadException(int error) {
super("recorder read error " + error);
}
}
================================================
FILE: library/src/main/java/com/liulishuo/engzo/lingorecorder/recorder/exception/RecorderStartException.java
================================================
package com.liulishuo.engzo.lingorecorder.recorder.exception;
/**
* Created by wcw on 1/26/18.
*/
public class RecorderStartException extends RecorderException {
public RecorderStartException() {
super("start Android audioRecorder error");
}
}
================================================
FILE: library/src/main/java/com/liulishuo/engzo/lingorecorder/utils/LOG.java
================================================
package com.liulishuo.engzo.lingorecorder.utils;
import android.text.TextUtils;
import android.util.Log;
/**
* Created by wcw on 3/28/17.
*/
public class LOG {
public static boolean isEnable = false;
public static final String TAG = "LingoRecorder";
public static void d(String log) {
if (isEnable && !TextUtils.isEmpty(log)) {
Log.d(TAG, log);
}
}
public static void e(Throwable throwable) {
if (isEnable && throwable != null) {
Log.e(TAG, Log.getStackTraceString(throwable));
}
}
public static void e(String message) {
if (isEnable && !TextUtils.isEmpty(message)) {
Log.e(TAG, message);
}
}
}
================================================
FILE: library/src/main/java/com/liulishuo/engzo/lingorecorder/utils/RecorderProperty.java
================================================
package com.liulishuo.engzo.lingorecorder.utils;
/**
* Created by rantianhua on 17/8/29.
* hold properties for a recorder
*/
public class RecorderProperty {
private int sampleRate;
private int channels;
private int bitsPerSample;
public RecorderProperty() {
setSampleRate(16000);
setChannels((short) 1);
setBitsPerSample(16);
}
public int getBitsPerSample() {
return bitsPerSample;
}
public RecorderProperty setBitsPerSample(int bitsPerSample) {
this.bitsPerSample = bitsPerSample;
return this;
}
public int getSampleRate() {
return sampleRate;
}
public RecorderProperty setSampleRate(int sampleRate) {
this.sampleRate = sampleRate;
return this;
}
public int getChannels() {
return channels;
}
public RecorderProperty setChannels(int channels) {
this.channels = channels;
return this;
}
}
================================================
FILE: library/src/main/java/com/liulishuo/engzo/lingorecorder/utils/WrapBuffer.java
================================================
package com.liulishuo.engzo.lingorecorder.utils;
public class WrapBuffer {
private byte[] bytes;
private int size;
public byte[] getBytes() {
return bytes;
}
public void setBytes(byte[] bytes) {
this.bytes = bytes;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
}
================================================
FILE: library/src/main/java/com/liulishuo/engzo/lingorecorder/volume/DefaultVolumeCalculator.java
================================================
package com.liulishuo.engzo.lingorecorder.volume;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
/**
* Created by rantianhua on 2017/9/26.
* provide a default volume calculator
*/
public class DefaultVolumeCalculator implements IVolumeCalculator {
/**
*
* @param chunk record chunk
* @param size size of chunk
* @param bitsPerSample bits per sample
* @return the volume decibels 0 - 90
*/
@Override
public double onAudioChunk(byte[] chunk, int size, int bitsPerSample) {
double sumVolume = 0.0;
double avgVolume;
if (bitsPerSample == 16) {
final ByteBuffer byteBuffer = ByteBuffer.wrap(chunk, 0, size);
final short[] buf = new short[size / 2];
byteBuffer.order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(buf);
for (short b : buf) {
sumVolume += Math.abs(b);
}
avgVolume = sumVolume / buf.length;
} else {
for (int i = 0; i < size; i++) {
sumVolume += Math.abs(chunk[i]);
}
avgVolume = sumVolume / size;
}
return 20 * Math.log10(avgVolume);
}
}
================================================
FILE: library/src/main/java/com/liulishuo/engzo/lingorecorder/volume/IVolumeCalculator.java
================================================
package com.liulishuo.engzo.lingorecorder.volume;
/**
* Created by rantianhua on 2017/9/26.
* calculate volume
*/
public interface IVolumeCalculator {
double onAudioChunk(byte[] chunk, int size, int bitsPerSample);
}
================================================
FILE: library/src/main/java/com/liulishuo/engzo/lingorecorder/volume/OnVolumeListener.java
================================================
package com.liulishuo.engzo.lingorecorder.volume;
/**
* Created by rantianhua on 2017/9/26.
* the callback of volume
*/
public interface OnVolumeListener {
void onVolume(double volume);
}
================================================
FILE: library/src/test/java/com/liulishuo/engzo/lingorecorder/ExampleUnitTest.java
================================================
package com.liulishuo.engzo.lingorecorder;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
================================================
FILE: settings.gradle
================================================
include ':demo' , ':lingo-recorder'
project(':lingo-recorder').projectDir = new File(settingsDir, 'library')
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
SYMBOL INDEX (266 symbols across 37 files)
FILE: demo/src/androidTest/java/com/liulishuo/engzo/lingorecorder/ExampleInstrumentedTest.java
class ExampleInstrumentedTest (line 17) | @RunWith(AndroidJUnit4.class)
method useAppContext (line 19) | @Test
FILE: demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/AndroidFlacProcessor.java
class AndroidFlacProcessor (line 19) | @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
method AndroidFlacProcessor (line 27) | public AndroidFlacProcessor() {
method AndroidFlacProcessor (line 30) | public AndroidFlacProcessor(String filePath) {
method setFilePath (line 34) | public void setFilePath(String filePath) {
method start (line 38) | @Override
method flow (line 57) | @Override
method needExit (line 89) | @Override
method end (line 94) | @Override
method getFilePath (line 113) | public String getFilePath() {
method release (line 117) | @Override
FILE: demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/LocalScorerProcessor.java
class LocalScorerProcessor (line 22) | public class LocalScorerProcessor implements AudioProcessor {
method LocalScorerProcessor (line 32) | public LocalScorerProcessor(Application application, String spokenTex...
method onServiceConnected (line 38) | @Override
method onServiceDisconnected (line 53) | @Override
method start (line 61) | @Override
method flow (line 78) | @Override
method needExit (line 83) | @Override
method end (line 93) | @Override
method release (line 99) | @Override
method getScore (line 112) | public int getScore() {
FILE: demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/RecordPermissionHelper.java
class RecordPermissionHelper (line 17) | public class RecordPermissionHelper {
method RecordPermissionHelper (line 25) | public RecordPermissionHelper(AppCompatActivity activity) {
method setGrantedListener (line 29) | public void setGrantedListener(
method checkRecordPermission (line 34) | public boolean checkRecordPermission() {
method onRequestPermissionsResult (line 72) | public void onRequestPermissionsResult(int requestCode, String[] permi...
type PermissionGrantedListener (line 88) | public interface PermissionGrantedListener {
method onPermissionGranted (line 89) | void onPermissionGranted();
FILE: demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/ScorerService.java
class ScorerService (line 19) | public class ScorerService extends Service {
method init (line 26) | @Override
method start (line 31) | @Override
method flow (line 36) | @Override
method needExit (line 41) | @Override
method end (line 46) | @Override
method release (line 51) | @Override
method getResult (line 56) | @Override
method onBind (line 62) | @Nullable
FILE: demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/Utils.java
class Utils (line 15) | public class Utils {
method getDurationString (line 18) | public static String getDurationString(long durationInMills) {
method formatFileSize (line 28) | public static String formatFileSize(String path) {
method checkSupportMediaCodec (line 41) | public static MediaCodecInfo checkSupportMediaCodec(String mimeType) {
method checkIsSpecifyCodec (line 70) | @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
FILE: demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/activity/AcrossProcessDemonstrateActivity.java
class AcrossProcessDemonstrateActivity (line 19) | public class AcrossProcessDemonstrateActivity extends RecordActivity {
method onCreate (line 26) | @Override
method onProcessError (line 53) | @Override
method onRecordError (line 59) | @Override
method onProcessStop (line 65) | @Override
method onRecordStop (line 73) | @Override
method onPermissionGranted (line 78) | @Override
FILE: demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/activity/DemoListActivity.java
class DemoListActivity (line 17) | public class DemoListActivity extends AppCompatActivity {
method onCreate (line 19) | @Override
method recordDemonstrate (line 25) | public void recordDemonstrate(View view) {
method processorsDemonstrate (line 29) | public void processorsDemonstrate(View view) {
method flacDemonstrate (line 33) | public void flacDemonstrate(View view) {
method acrossProcessDemonstrate (line 37) | public void acrossProcessDemonstrate(View view) {
method volumeDemonstrate (line 41) | public void volumeDemonstrate(View view) {
FILE: demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/activity/FlacDemonstrateActivity.java
class FlacDemonstrateActivity (line 23) | public class FlacDemonstrateActivity extends RecordActivity {
method onCreate (line 35) | @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
method checkSupportFlac (line 79) | private boolean checkSupportFlac() {
method onRecordError (line 83) | @Override
method onProcessError (line 89) | @Override
method onProcessStop (line 95) | @Override
method onRecordStop (line 101) | @Override
method onPermissionGranted (line 107) | @Override
FILE: demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/activity/ProcessorsDemonstrateActivity.java
class ProcessorsDemonstrateActivity (line 33) | public class ProcessorsDemonstrateActivity extends RecordActivity {
method onCreate (line 49) | @Override
method initHandler (line 89) | private void initHandler() {
method initLingoRecorder (line 107) | private void initLingoRecorder() {
method onProcessStop (line 220) | @Override
method onRecordStop (line 225) | @Override
method onPermissionGranted (line 230) | @Override
class ProcessorAdapter (line 235) | static class ProcessorAdapter extends RecyclerView.Adapter<ProcessorAd...
method ProcessorAdapter (line 239) | ProcessorAdapter() {
method onCreateViewHolder (line 243) | @Override
method dpToPx (line 254) | int dpToPx(Context context, int dp) {
method onBindViewHolder (line 259) | @Override
method getItemCount (line 265) | @Override
method addData (line 270) | void addData(String item) {
class VH (line 278) | static class VH extends RecyclerView.ViewHolder {
method VH (line 282) | VH(View itemView) {
FILE: demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/activity/RecordActivity.java
class RecordActivity (line 22) | public abstract class RecordActivity extends AppCompatActivity {
method onCreate (line 29) | @Override
method onProcessError (line 64) | protected void onProcessError(Throwable throwable) {
method onRecordError (line 69) | protected void onRecordError(Throwable throwable) {
method onRequestPermissionsResult (line 74) | @Override
method checkRecordPermission (line 81) | protected boolean checkRecordPermission() {
method onDestroy (line 85) | @Override
method onProcessStop (line 93) | protected abstract void onProcessStop(Map<String, AudioProcessor> map);
method onRecordStop (line 95) | protected abstract void onRecordStop(LingoRecorder.OnRecordStopListene...
method onPermissionGranted (line 97) | protected abstract void onPermissionGranted();
FILE: demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/activity/RecordDemonstrateActivity.java
class RecordDemonstrateActivity (line 31) | public class RecordDemonstrateActivity extends RecordActivity {
method onCreate (line 42) | @Override
method handleRecorderBtn (line 91) | private void handleRecorderBtn() {
method onRecordError (line 101) | @Override
method onProcessError (line 107) | @Override
method onProcessStop (line 113) | @Override
method onRecordStop (line 120) | @Override
method onPermissionGranted (line 127) | @Override
FILE: demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/activity/VolumeDemonstrateActivity.java
class VolumeDemonstrateActivity (line 23) | public class VolumeDemonstrateActivity extends RecordActivity {
method onCreate (line 29) | @Override
method handleRecorderBtn (line 58) | private void handleRecorderBtn() {
method onRecordError (line 68) | @Override
method onProcessError (line 74) | @Override
method onProcessStop (line 80) | @Override
method onRecordStop (line 85) | @Override
method onPermissionGranted (line 90) | @Override
FILE: demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/view/VolumeView.java
class VolumeView (line 24) | public class VolumeView extends View {
method VolumeView (line 36) | public VolumeView(Context context) {
method VolumeView (line 41) | public VolumeView(Context context, @Nullable AttributeSet attrs) {
method VolumeView (line 46) | public VolumeView(Context context, @Nullable AttributeSet attrs, int d...
method VolumeView (line 51) | @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
method init (line 57) | private void init() {
method onDraw (line 75) | @Override
method calculateSample (line 97) | private void calculateSample(int width) {
method setAmplitude (line 106) | public void setAmplitude(double amplitude) {
method startWave (line 110) | public void startWave() {
method stopWave (line 117) | public void stopWave() {
method onDetachedFromWindow (line 123) | @Override
FILE: demo/src/test/java/com/liulishuo/engzo/lingorecorder/ExampleUnitTest.java
class ExampleUnitTest (line 12) | public class ExampleUnitTest {
method addition_isCorrect (line 13) | @Test
FILE: library/src/androidTest/java/com/liulishuo/engzo/lingorecorder/CancelRecordTest.java
class CancelRecordTest (line 26) | @RunWith(AndroidJUnit4.class)
method before (line 37) | @Before
method testCancelRecorderWhenProcessingBlock (line 42) | @Test
FILE: library/src/androidTest/java/com/liulishuo/engzo/lingorecorder/LingoRecorderTest.java
class LingoRecorderTest (line 24) | @RunWith(AndroidJUnit4.class)
method before (line 30) | @Before
method testRecorderStopWhenProcessorThrowException (line 35) | @Test
method getFileSize (line 97) | private long getFileSize(String file) {
FILE: library/src/androidTest/java/com/liulishuo/engzo/lingorecorder/RecordAndProcessorEndTest.java
class RecordAndProcessorEndTest (line 23) | @RunWith(AndroidJUnit4.class)
method before (line 32) | @Before
method recorderEndFirstRecorderCallbackFirst (line 37) | @Test
method sleep (line 97) | private void sleep() {
method processorMayEndFirstRecorderCallbackFirst (line 106) | @Test
FILE: library/src/main/java/com/liulishuo/engzo/lingorecorder/LingoRecorder.java
class LingoRecorder (line 33) | public class LingoRecorder {
method LingoRecorder (line 56) | public LingoRecorder() {
method isProcessing (line 60) | public boolean isProcessing() {
method isAvailable (line 68) | @Deprecated
method isRecording (line 73) | public boolean isRecording() {
method start (line 77) | public boolean start() {
method start (line 81) | public boolean start(String outputFilePath) {
method stop (line 117) | public void stop() {
method cancel (line 127) | public void cancel() {
method setOnRecordStopListener (line 135) | public void setOnRecordStopListener(OnRecordStopListener onRecordStopL...
method setOnProcessStopListener (line 139) | public void setOnProcessStopListener(OnProcessStopListener onProcessSt...
method setOnVolumeListener (line 143) | public void setOnVolumeListener(OnVolumeListener onVolumeListener) {
method setOnVolumeListener (line 147) | public void setOnVolumeListener(OnVolumeListener onVolumeListener, IVo...
method put (line 152) | public void put(String processorId, AudioProcessor processor) {
method remove (line 156) | public AudioProcessor remove(String processorId) {
type OnRecordStopListener (line 160) | public interface OnRecordStopListener {
class Result (line 162) | class Result {
method getDurationInMills (line 166) | public long getDurationInMills() {
method getOutputFilePath (line 170) | public String getOutputFilePath() {
method onRecordStop (line 175) | void onRecordStop(Throwable throwable, Result result);
type OnProcessStopListener (line 178) | public interface OnProcessStopListener {
method onProcessStop (line 179) | void onProcessStop(Throwable throwable, Map<String, AudioProcessor> ...
method sampleRate (line 182) | public LingoRecorder sampleRate(int sampleRate) {
method channels (line 187) | public LingoRecorder channels(int channels) {
method bitsPerSample (line 192) | public LingoRecorder bitsPerSample(int bitsPerSample) {
method getRecorderProperty (line 197) | public RecorderProperty getRecorderProperty() {
method wavFile (line 201) | public LingoRecorder wavFile(String filePath) {
class InternalRecorder (line 206) | private static class InternalRecorder implements Runnable {
method InternalRecorder (line 219) | InternalRecorder(
method cancel (line 233) | void cancel() {
method stop (line 238) | void stop() {
method start (line 242) | void start() {
method run (line 246) | @Override
class ProcessThread (line 337) | class ProcessThread extends Thread {
method ProcessThread (line 341) | ProcessThread() {
method ProcessThread (line 345) | ProcessThread(final LinkedBlockingQueue<Object> processorQueue) {
method process (line 350) | void process(@NonNull byte[] bytes, int buffSize) throws Interrupt...
method end (line 357) | void end(boolean cancel) {
method run (line 370) | @Override
method checkIfNeedCancel (line 417) | private void checkIfNeedCancel() {
class RecorderHandler (line 424) | private static class RecorderHandler extends Handler {
method RecorderHandler (line 429) | RecorderHandler(LingoRecorder lingoRecorder, Map<String, AudioProces...
method handleMessage (line 435) | @Override
method handleRecordStop (line 457) | private void handleRecordStop(Message msg) {
method handleProcessStop (line 469) | private void handleProcessStop(Message msg) {
class CancelProcessingException (line 477) | public static class CancelProcessingException extends RuntimeException {
method CancelProcessingException (line 479) | public CancelProcessingException() {
method CancelProcessingException (line 483) | public CancelProcessingException(Throwable throwable) {
class RecordErrorCancelProcessingException (line 488) | public static class RecordErrorCancelProcessingException extends Cance...
method RecordErrorCancelProcessingException (line 490) | public RecordErrorCancelProcessingException(Throwable throwable) {
method setDebugEnable (line 495) | public void setDebugEnable(boolean enable) {
FILE: library/src/main/java/com/liulishuo/engzo/lingorecorder/processor/AudioProcessor.java
type AudioProcessor (line 7) | public interface AudioProcessor {
method start (line 9) | void start() throws Exception;
method flow (line 11) | void flow(byte[] bytes, int size) throws Exception;
method needExit (line 13) | boolean needExit();
method end (line 15) | void end() throws Exception;
method release (line 17) | void release();
FILE: library/src/main/java/com/liulishuo/engzo/lingorecorder/processor/TimerProcessor.java
class TimerProcessor (line 5) | public class TimerProcessor implements AudioProcessor {
method TimerProcessor (line 13) | public TimerProcessor(long timeInMills) {
method TimerProcessor (line 17) | public TimerProcessor(RecorderProperty recorderProperty, long timeInMi...
method start (line 22) | @Override
method flow (line 27) | @Override
method needExit (line 32) | @Override
method end (line 41) | @Override
method release (line 46) | @Override
FILE: library/src/main/java/com/liulishuo/engzo/lingorecorder/processor/WavProcessor.java
class WavProcessor (line 13) | public class WavProcessor implements AudioProcessor {
method WavProcessor (line 21) | public WavProcessor(String filePath) {
method WavProcessor (line 25) | public WavProcessor(String filePath, RecorderProperty recordProperty) {
method start (line 30) | @Override
method flow (line 66) | @Override
method needExit (line 74) | @Override
method end (line 79) | @Override
method release (line 88) | @Override
method getFilePath (line 100) | public String getFilePath() {
method getRecordProperty (line 104) | public RecorderProperty getRecordProperty() {
FILE: library/src/main/java/com/liulishuo/engzo/lingorecorder/recorder/AndroidRecorder.java
class AndroidRecorder (line 20) | public class AndroidRecorder implements IRecorder {
method AndroidRecorder (line 29) | public AndroidRecorder(final RecorderProperty recorderProperty) {
method getBufferSize (line 49) | @Override
method startRecording (line 60) | @Override
method read (line 79) | @Override
method release (line 89) | @Override
method getDurationInMills (line 96) | @Override
method getRecordProperty (line 102) | @Override
FILE: library/src/main/java/com/liulishuo/engzo/lingorecorder/recorder/IRecorder.java
type IRecorder (line 12) | public interface IRecorder {
method getBufferSize (line 14) | int getBufferSize() throws Throwable;
method startRecording (line 16) | void startRecording() throws Throwable;
method read (line 18) | int read(@NonNull byte[] bytes, int buffSize) throws Throwable;
method release (line 20) | void release();
method getDurationInMills (line 22) | long getDurationInMills();
method getRecordProperty (line 24) | RecorderProperty getRecordProperty();
FILE: library/src/main/java/com/liulishuo/engzo/lingorecorder/recorder/WavFileRecorder.java
class WavFileRecorder (line 14) | public class WavFileRecorder implements IRecorder {
method WavFileRecorder (line 22) | public WavFileRecorder(String filePath, RecorderProperty recorderPrope...
method getBufferSize (line 27) | @Override
method startRecording (line 32) | @Override
method read (line 40) | @Override
method release (line 47) | @Override
method getDurationInMills (line 56) | @Override
method getRecordProperty (line 62) | @Override
FILE: library/src/main/java/com/liulishuo/engzo/lingorecorder/recorder/exception/RecorderException.java
class RecorderException (line 7) | public class RecorderException extends RuntimeException {
method RecorderException (line 9) | public RecorderException(String message) {
FILE: library/src/main/java/com/liulishuo/engzo/lingorecorder/recorder/exception/RecorderGetBufferSizeException.java
class RecorderGetBufferSizeException (line 7) | public class RecorderGetBufferSizeException extends RecorderException {
method RecorderGetBufferSizeException (line 9) | public RecorderGetBufferSizeException(int error) {
FILE: library/src/main/java/com/liulishuo/engzo/lingorecorder/recorder/exception/RecorderInitException.java
class RecorderInitException (line 7) | public class RecorderInitException extends RecorderException {
method RecorderInitException (line 9) | public RecorderInitException() {
FILE: library/src/main/java/com/liulishuo/engzo/lingorecorder/recorder/exception/RecorderReadException.java
class RecorderReadException (line 7) | public class RecorderReadException extends RecorderException {
method RecorderReadException (line 9) | public RecorderReadException(int error) {
FILE: library/src/main/java/com/liulishuo/engzo/lingorecorder/recorder/exception/RecorderStartException.java
class RecorderStartException (line 7) | public class RecorderStartException extends RecorderException {
method RecorderStartException (line 9) | public RecorderStartException() {
FILE: library/src/main/java/com/liulishuo/engzo/lingorecorder/utils/LOG.java
class LOG (line 10) | public class LOG {
method d (line 16) | public static void d(String log) {
method e (line 22) | public static void e(Throwable throwable) {
method e (line 28) | public static void e(String message) {
FILE: library/src/main/java/com/liulishuo/engzo/lingorecorder/utils/RecorderProperty.java
class RecorderProperty (line 8) | public class RecorderProperty {
method RecorderProperty (line 14) | public RecorderProperty() {
method getBitsPerSample (line 20) | public int getBitsPerSample() {
method setBitsPerSample (line 24) | public RecorderProperty setBitsPerSample(int bitsPerSample) {
method getSampleRate (line 29) | public int getSampleRate() {
method setSampleRate (line 33) | public RecorderProperty setSampleRate(int sampleRate) {
method getChannels (line 38) | public int getChannels() {
method setChannels (line 42) | public RecorderProperty setChannels(int channels) {
FILE: library/src/main/java/com/liulishuo/engzo/lingorecorder/utils/WrapBuffer.java
class WrapBuffer (line 3) | public class WrapBuffer {
method getBytes (line 8) | public byte[] getBytes() {
method setBytes (line 12) | public void setBytes(byte[] bytes) {
method getSize (line 16) | public int getSize() {
method setSize (line 20) | public void setSize(int size) {
FILE: library/src/main/java/com/liulishuo/engzo/lingorecorder/volume/DefaultVolumeCalculator.java
class DefaultVolumeCalculator (line 11) | public class DefaultVolumeCalculator implements IVolumeCalculator {
method onAudioChunk (line 20) | @Override
FILE: library/src/main/java/com/liulishuo/engzo/lingorecorder/volume/IVolumeCalculator.java
type IVolumeCalculator (line 8) | public interface IVolumeCalculator {
method onAudioChunk (line 10) | double onAudioChunk(byte[] chunk, int size, int bitsPerSample);
FILE: library/src/main/java/com/liulishuo/engzo/lingorecorder/volume/OnVolumeListener.java
type OnVolumeListener (line 8) | public interface OnVolumeListener {
method onVolume (line 10) | void onVolume(double volume);
FILE: library/src/test/java/com/liulishuo/engzo/lingorecorder/ExampleUnitTest.java
class ExampleUnitTest (line 12) | public class ExampleUnitTest {
method addition_isCorrect (line 13) | @Test
Condensed preview — 69 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (160K chars).
[
{
"path": ".gitignore",
"chars": 134,
"preview": "# Created by .ignore support plugin (hsz.mobi)\nbuild\n.gradle\nlocal.properties\n.idea/workspace.xml\n.idea/libraries\n.idea/"
},
{
"path": "LICENSE.txt",
"chars": 11358,
"preview": "\n Apache License\n Version 2.0, January 2004\n "
},
{
"path": "README.md",
"chars": 3263,
"preview": "# LingoRecorder\n\nLingoRecord is a better recorder for Android, you can easily process pcm data from it.\n\n[  2018 LingoChamp Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you ma"
},
{
"path": "gradle/mvn-local.gradle",
"chars": 1724,
"preview": "/*\n * Copyright (c) 2018 LingoChamp Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you ma"
},
{
"path": "gradle/mvn-push.gradle",
"chars": 5825,
"preview": "/*\n * Copyright 2013 Chris Banes\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not us"
},
{
"path": "gradle/wrapper/gradle-wrapper.properties",
"chars": 232,
"preview": "#Mon Jul 31 15:15:58 CST 2017\ndistributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER_"
},
{
"path": "gradle.properties",
"chars": 1378,
"preview": "# Project-wide Gradle settings.\n\n# IDE (e.g. Android Studio) users:\n# Gradle settings configured through the IDE *will o"
},
{
"path": "gradlew",
"chars": 4971,
"preview": "#!/usr/bin/env bash\n\n##############################################################################\n##\n## Gradle start "
},
{
"path": "gradlew.bat",
"chars": 2314,
"preview": "@if \"%DEBUG%\" == \"\" @echo off\n@rem ##########################################################################\n@rem\n@rem "
},
{
"path": "library/build.gradle",
"chars": 1037,
"preview": "apply plugin: 'com.android.library'\n\nandroid {\n compileSdkVersion 28\n\n defaultConfig {\n minSdkVersion 15\n "
},
{
"path": "library/gradle.properties",
"chars": 174,
"preview": "POM_ARTIFACT_ID=lingo-recorder\nPOM_NAME=LingoRecorder\nPOM_DESCRIPTION=LingoRecord is a better recorder for Android, you "
},
{
"path": "library/proguard-rules.pro",
"chars": 649,
"preview": "# Add project specific ProGuard rules here.\n# By default, the flags in this file are appended to flags specified\n# in /U"
},
{
"path": "library/src/androidTest/AndroidManifest.xml",
"chars": 385,
"preview": "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.liulishuo.engzo.lingorecorder\">\n\n "
},
{
"path": "library/src/androidTest/java/com/liulishuo/engzo/lingorecorder/CancelRecordTest.java",
"chars": 3285,
"preview": "package com.liulishuo.engzo.lingorecorder;\n\nimport android.Manifest;\nimport android.util.Log;\n\nimport androidx.test.filt"
},
{
"path": "library/src/androidTest/java/com/liulishuo/engzo/lingorecorder/LingoRecorderTest.java",
"chars": 2543,
"preview": "package com.liulishuo.engzo.lingorecorder;\n\nimport androidx.test.filters.SmallTest;\nimport androidx.test.runner.AndroidJ"
},
{
"path": "library/src/androidTest/java/com/liulishuo/engzo/lingorecorder/RecordAndProcessorEndTest.java",
"chars": 4695,
"preview": "package com.liulishuo.engzo.lingorecorder;\n\nimport androidx.test.filters.SmallTest;\nimport androidx.test.runner.AndroidJ"
},
{
"path": "library/src/main/AndroidManifest.xml",
"chars": 232,
"preview": "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.liulishuo.engzo.lingorecorder\">\n\n "
},
{
"path": "library/src/main/aidl/com/liulishuo/engzo/IAudioProcessorService.aidl",
"chars": 251,
"preview": "package com.liulishuo.engzo;\n\ninterface IAudioProcessorService {\n\n void init(in Bundle bundle);\n\n void start();\n "
},
{
"path": "library/src/main/java/com/liulishuo/engzo/lingorecorder/LingoRecorder.java",
"chars": 17176,
"preview": "package com.liulishuo.engzo.lingorecorder;\n\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.Loope"
},
{
"path": "library/src/main/java/com/liulishuo/engzo/lingorecorder/processor/AudioProcessor.java",
"chars": 303,
"preview": "package com.liulishuo.engzo.lingorecorder.processor;\n\n/**\n * Created by wcw on 3/28/17.\n */\n\npublic interface AudioProce"
},
{
"path": "library/src/main/java/com/liulishuo/engzo/lingorecorder/processor/TimerProcessor.java",
"chars": 1201,
"preview": "package com.liulishuo.engzo.lingorecorder.processor;\n\nimport com.liulishuo.engzo.lingorecorder.utils.RecorderProperty;\n\n"
},
{
"path": "library/src/main/java/com/liulishuo/engzo/lingorecorder/processor/WavProcessor.java",
"chars": 3590,
"preview": "package com.liulishuo.engzo.lingorecorder.processor;\n\nimport com.liulishuo.engzo.lingorecorder.utils.RecorderProperty;\n\n"
},
{
"path": "library/src/main/java/com/liulishuo/engzo/lingorecorder/recorder/AndroidRecorder.java",
"chars": 3518,
"preview": "package com.liulishuo.engzo.lingorecorder.recorder;\n\nimport android.media.AudioFormat;\nimport android.media.AudioRecord;"
},
{
"path": "library/src/main/java/com/liulishuo/engzo/lingorecorder/recorder/IRecorder.java",
"chars": 479,
"preview": "package com.liulishuo.engzo.lingorecorder.recorder;\n\n\nimport androidx.annotation.NonNull;\n\nimport com.liulishuo.engzo.li"
},
{
"path": "library/src/main/java/com/liulishuo/engzo/lingorecorder/recorder/WavFileRecorder.java",
"chars": 1646,
"preview": "package com.liulishuo.engzo.lingorecorder.recorder;\n\nimport androidx.annotation.NonNull;\n\nimport com.liulishuo.engzo.lin"
},
{
"path": "library/src/main/java/com/liulishuo/engzo/lingorecorder/recorder/exception/RecorderException.java",
"chars": 242,
"preview": "package com.liulishuo.engzo.lingorecorder.recorder.exception;\n\n/**\n * Created by wcw on 1/26/18.\n */\n\npublic class Recor"
},
{
"path": "library/src/main/java/com/liulishuo/engzo/lingorecorder/recorder/exception/RecorderGetBufferSizeException.java",
"chars": 296,
"preview": "package com.liulishuo.engzo.lingorecorder.recorder.exception;\n\n/**\n * Created by wcw on 1/26/18.\n */\n\npublic class Recor"
},
{
"path": "library/src/main/java/com/liulishuo/engzo/lingorecorder/recorder/exception/RecorderInitException.java",
"chars": 262,
"preview": "package com.liulishuo.engzo.lingorecorder.recorder.exception;\n\n/**\n * Created by wcw on 1/26/18.\n */\n\npublic class Recor"
},
{
"path": "library/src/main/java/com/liulishuo/engzo/lingorecorder/recorder/exception/RecorderReadException.java",
"chars": 267,
"preview": "package com.liulishuo.engzo.lingorecorder.recorder.exception;\n\n/**\n * Created by wcw on 1/26/18.\n */\n\npublic class Recor"
},
{
"path": "library/src/main/java/com/liulishuo/engzo/lingorecorder/recorder/exception/RecorderStartException.java",
"chars": 265,
"preview": "package com.liulishuo.engzo.lingorecorder.recorder.exception;\n\n/**\n * Created by wcw on 1/26/18.\n */\n\npublic class Recor"
},
{
"path": "library/src/main/java/com/liulishuo/engzo/lingorecorder/utils/LOG.java",
"chars": 721,
"preview": "package com.liulishuo.engzo.lingorecorder.utils;\n\nimport android.text.TextUtils;\nimport android.util.Log;\n\n/**\n * Create"
},
{
"path": "library/src/main/java/com/liulishuo/engzo/lingorecorder/utils/RecorderProperty.java",
"chars": 966,
"preview": "package com.liulishuo.engzo.lingorecorder.utils;\n\n/**\n * Created by rantianhua on 17/8/29.\n * hold properties for a reco"
},
{
"path": "library/src/main/java/com/liulishuo/engzo/lingorecorder/utils/WrapBuffer.java",
"chars": 386,
"preview": "package com.liulishuo.engzo.lingorecorder.utils;\n\npublic class WrapBuffer {\n\n private byte[] bytes;\n private int s"
},
{
"path": "library/src/main/java/com/liulishuo/engzo/lingorecorder/volume/DefaultVolumeCalculator.java",
"chars": 1195,
"preview": "package com.liulishuo.engzo.lingorecorder.volume;\n\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\n\n/**\n * Create"
},
{
"path": "library/src/main/java/com/liulishuo/engzo/lingorecorder/volume/IVolumeCalculator.java",
"chars": 227,
"preview": "package com.liulishuo.engzo.lingorecorder.volume;\n\n/**\n * Created by rantianhua on 2017/9/26.\n * calculate volume\n */\n\np"
},
{
"path": "library/src/main/java/com/liulishuo/engzo/lingorecorder/volume/OnVolumeListener.java",
"chars": 199,
"preview": "package com.liulishuo.engzo.lingorecorder.volume;\n\n/**\n * Created by rantianhua on 2017/9/26.\n * the callback of volume\n"
},
{
"path": "library/src/test/java/com/liulishuo/engzo/lingorecorder/ExampleUnitTest.java",
"chars": 411,
"preview": "package com.liulishuo.engzo.lingorecorder;\n\nimport org.junit.Test;\n\nimport static org.junit.Assert.*;\n\n/**\n * Example lo"
},
{
"path": "settings.gradle",
"chars": 111,
"preview": "include ':demo' , ':lingo-recorder'\n\nproject(':lingo-recorder').projectDir = new File(settingsDir, 'library')\n\n"
}
]
// ... and 1 more files (download for full content)
About this extraction
This page contains the full source code of the lingochamp/LingoRecorder GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 69 files (143.5 KB), approximately 34.9k tokens, and a symbol index with 266 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.