[
  {
    "path": ".gitignore",
    "content": "# Created by .ignore support plugin (hsz.mobi)\nbuild\n.gradle\nlocal.properties\n.idea/workspace.xml\n.idea/libraries\n.idea/misc.xml\n*.iml"
  },
  {
    "path": "LICENSE.txt",
    "content": "\n                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright (c) 2017 LingoChamp Inc.\n   \n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n   \n      http://www.apache.org/licenses/LICENSE-2.0\n   \n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# LingoRecorder\n\nLingoRecord is a better recorder for Android, you can easily process pcm data from it.\n\n[ ![Download](https://api.bintray.com/packages/wangcongwu123/maven/LingoRecorder/images/download.svg) ](https://bintray.com/wangcongwu123/maven/LingoRecorder/_latestVersion)\n\n\n# Features\n\n1. 多线程机制保证处理能力和 PCM 数据的完整性。\n\n2. 抽象出 AudioProcessor 来注入 Recorder 中以支持录音和处理的分离。\n\n3. 提供 WavFileRecorder 以支持以文件来替代录音器生成录音数据。\n\n4. 提供 aidl 接口方便在另一个进程中处理录音数据。\n\n# Sample\n\n## LingoRecorder 的使用\n\n只需简单的三步操作即可:\n\n```\nlingoRecorder = new LingoRecorder();\nlingoRecorder.setOnRecordStopListener(new LingoRecorder.OnRecordStopListener() {\n    @Override\n    public void onRecordStop(Throwable throwable,\n        Result result) {\n        //any execeptions occur during recording will be received at here.\n        //you can get duration and output file from Result.\n    }\n});\nlingoRecorder.setOnProcessStopListener(new LingoRecorder.OnProcessStopListener() {\n    @Override\n    public void onProcessStop(Throwable throwable, Map<String, AudioProcessor> map) {\n        //any execeptions occur during processing will be received at here.\n        //you can get any processors you inject into recorder.\n        //the callback will be invoked after \"onRecordStop\".\n    }\n});\n```\n\n效果图:\n\n![image](https://raw.github.com/lingochamp/LingoRecorder/develop/demo/images/record.gif)\n\n## 自定义 AudioProcessor 的使用\n\n可以实现 AudioProcessor 来自定义自己的处理器：\n\n```\npublic interface AudioProcessor {\n\n    void start() throws Exception;\n\n    void flow(byte[] bytes, int size) throws Exception;\n\n    boolean needExit();\n\n    void end() throws Exception;\n\n    void release();\n\n}\n```\n\n效果图:\n\n![image](https://raw.github.com/lingochamp/LingoRecorder/develop/demo/images/custom_processors.gif)\n\n## 将 AudioProcessor 运行在一个独立的进程中\n\nLingoRecorder 提供了 aidl 接口以支持在一个独立的进程中运行 AudioProcessor。示例中自定义了一个 `LocalScorerProcessor` 运行在 \"score\" 进程中。\n\n## Flac encoder\n\n示例中也演示了一个使用 `MediaCodec` 进行 Flac 编码的 AudioProcessor。此示例是为了向有硬编码需求的用户提供一个样例。\n\n## 计算/监听音量\n\n设置音量监听器：\n\n```\n//只设置 OnVolumeListener 的时候，计算音量的方式使用的是一个默认的内部实现\n//内部默认实现的返回值是[0, 90]的分贝值\nlingoRecorder.setOnVolumeListener(new OnVolumeListener() {\n\t@Override\n\tpublic void onVolume(double volume) {\n\n\t}\n});\n//也可以提供自己的计算音量的实现\nlingoRecorder.setOnVolumeListener(new OnVolumeListener() {\n\t@Override\n\tpublic void onVolume(double volume) {\n\n\t}\n}, new IVolumeCalculator() {\n\t@Override\n\tpublic double onAudioChunk(byte[] chunk, int size, int bitsPerSample) {\n\t\treturn 0;\n\t}\n});\n```\nDemo 中提供了相关示例，效果图：\n\n![image](https://raw.github.com/lingochamp/LingoRecorder/develop/demo/images/volume.gif)\n\n\n# 在项目中引用\n\nGradle:\n\n```\ncompile 'com.liulishuo.engzo:lingo-recorder:1.2.5'\n\n```\n\n# Pull Request  \n欢迎各位基于 develop 分支进行 pull request。\n\nLicense\n-------\n\n    Licensed under the Apache License, Version 2.0 (the \"License\");\n    you may not use this file except in compliance with the License.\n    You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n"
  },
  {
    "path": "build.gradle",
    "content": "// Top-level build file where you can add configuration options common to all sub-projects/modules.\n\nbuildscript {\n    repositories {\n        jcenter()\n        google()\n    }\n    dependencies {\n        classpath 'com.android.tools.build:gradle:3.5.3'\n        classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.8.4'\n    }\n}\n\nallprojects {\n    repositories {\n        jcenter()\n        google()\n    }\n}\n\nsubprojects {\n    group = GROUP\n    version = VERSION_NAME\n}\n\ntask clean(type: Delete) {\n    delete rootProject.buildDir\n}\n"
  },
  {
    "path": "build_aar.sh",
    "content": "./gradlew clean build generateRelease -p library\n"
  },
  {
    "path": "demo/build.gradle",
    "content": "apply plugin: 'com.android.application'\n\nandroid {\n    compileSdkVersion 28\n    defaultConfig {\n        applicationId \"com.liulishuo.engzo.lingorecorder.demo\"\n        minSdkVersion 15\n        targetSdkVersion 28\n        versionCode 1\n        versionName \"1.0\"\n        testInstrumentationRunner \"androidx.test.runner.AndroidJUnitRunner\"\n    }\n    buildTypes {\n        release {\n            minifyEnabled false\n            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\n        }\n    }\n}\n\ndependencies {\n    implementation fileTree(dir: 'libs', include: ['*.jar'])\n    androidTestImplementation('androidx.test.espresso:espresso-core:3.1.0', {\n        exclude group: 'com.android.support', module: 'support-annotations'\n    })\n\n    implementation project(\":lingo-recorder\")\n//    compile 'com.liulishuo.engzo:lingo-recorder:1.2.5'\n    implementation 'androidx.appcompat:appcompat:1.1.0'\n    implementation 'androidx.recyclerview:recyclerview:1.1.0'\n    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'\n    testImplementation 'junit:junit:4.12'\n}\n"
  },
  {
    "path": "demo/proguard-rules.pro",
    "content": "# Add project specific ProGuard rules here.\n# By default, the flags in this file are appended to flags specified\n# in /Users/wcw/dev/sdk/tools/proguard/proguard-android.txt\n# You can edit the include path and order by changing the proguardFiles\n# directive in build.gradle.\n#\n# For more details, see\n#   http://developer.android.com/guide/developing/tools/proguard.html\n\n# Add any project specific keep options here:\n\n# If your project uses WebView with JS, uncomment the following\n# and specify the fully qualified class name to the JavaScript interface\n# class:\n#-keepclassmembers class fqcn.of.javascript.interface.for.webview {\n#   public *;\n#}\n\n# Uncomment this to preserve the line number information for\n# debugging stack traces.\n#-keepattributes SourceFile,LineNumberTable\n\n# If you keep the line number information, uncomment this to\n# hide the original source file name.\n#-renamesourcefileattribute SourceFile\n"
  },
  {
    "path": "demo/src/androidTest/java/com/liulishuo/engzo/lingorecorder/ExampleInstrumentedTest.java",
    "content": "package com.liulishuo.engzo.lingorecorder;\n\nimport android.content.Context;\nimport android.support.test.InstrumentationRegistry;\nimport android.support.test.runner.AndroidJUnit4;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\n\nimport static org.junit.Assert.*;\n\n/**\n * Instrumentation test, which will execute on an Android device.\n *\n * @see <a href=\"http://d.android.com/tools/testing\">Testing documentation</a>\n */\n@RunWith(AndroidJUnit4.class)\npublic class ExampleInstrumentedTest {\n    @Test\n    public void useAppContext() throws Exception {\n        // Context of the app under test.\n        Context appContext = InstrumentationRegistry.getTargetContext();\n\n        assertEquals(\"com.liulishuo.engzo.lingorecorder\", appContext.getPackageName());\n    }\n}\n"
  },
  {
    "path": "demo/src/main/AndroidManifest.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    package=\"com.liulishuo.engzo.lingorecorder.demo\">\n\n    <uses-permission android:name=\"android.permission.RECORD_AUDIO\" />\n    <uses-permission android:name=\"android.permission.INTERNET\" />\n    <uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\" />\n\n    <application\n        android:allowBackup=\"true\"\n        android:icon=\"@mipmap/ic_launcher\"\n        android:label=\"@string/app_name\"\n        android:roundIcon=\"@mipmap/ic_launcher_round\"\n        android:supportsRtl=\"true\"\n        android:theme=\"@style/AppTheme\">\n        <activity android:name=\".activity.DemoListActivity\">\n            <intent-filter>\n                <action android:name=\"android.intent.action.MAIN\" />\n                <action android:name=\"android.intent.action.VIEW\" />\n\n                <category android:name=\"android.intent.category.LAUNCHER\" />\n            </intent-filter>\n        </activity>\n        <activity\n            android:name=\".activity.RecordDemonstrateActivity\"\n            android:screenOrientation=\"portrait\" />\n        <activity\n            android:name=\".activity.ProcessorsDemonstrateActivity\"\n            android:screenOrientation=\"portrait\" />\n        <activity\n            android:name=\".activity.FlacDemonstrateActivity\"\n            android:screenOrientation=\"portrait\" />\n\n        <activity\n            android:name=\".activity.AcrossProcessDemonstrateActivity\"\n            android:screenOrientation=\"portrait\" />\n\n        <activity\n            android:name=\".activity.VolumeDemonstrateActivity\"\n            android:screenOrientation=\"portrait\" />\n\n        <service\n            android:name=\".ScorerService\"\n            android:process=\":scorer\" />\n\n        <provider\n            android:authorities=\"com.liulishuo.engzo.lingorecorder.demo.fileProvider\"\n            android:name=\"androidx.core.content.FileProvider\"\n            android:grantUriPermissions=\"true\"\n            android:exported=\"false\">\n\n            <meta-data\n                android:name=\"android.support.FILE_PROVIDER_PATHS\"\n                android:resource=\"@xml/file_paths\" />\n\n        </provider>\n    </application>\n\n</manifest>"
  },
  {
    "path": "demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/AndroidFlacProcessor.java",
    "content": "package com.liulishuo.engzo.lingorecorder.demo;\n\nimport android.media.MediaCodec;\nimport android.media.MediaFormat;\nimport android.os.Build;\n\nimport androidx.annotation.RequiresApi;\n\nimport com.liulishuo.engzo.lingorecorder.processor.AudioProcessor;\nimport com.liulishuo.engzo.lingorecorder.utils.LOG;\n\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\n\n/**\n * Created by wcw on 3/30/17.\n */\n@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)\npublic class AndroidFlacProcessor implements AudioProcessor {\n\n    private String filePath;\n    private MediaCodec codec;\n\n    private FileOutputStream fos;\n\n    public AndroidFlacProcessor() {\n    }\n\n    public AndroidFlacProcessor(String filePath) {\n        this.filePath = filePath;\n    }\n\n    public void setFilePath(String filePath) {\n        this.filePath = filePath;\n    }\n\n    @Override\n    public void start() throws IOException {\n        try {\n            fos = new FileOutputStream(filePath);\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n\n        String mime = \"audio/flac\";\n        MediaFormat format = MediaFormat.createAudioFormat(mime, 16000, 1);\n        codec = MediaCodec.createEncoderByType(mime);\n        codec.configure(\n                format,\n                null /* surface */,\n                null /* crypto */,\n                MediaCodec.CONFIGURE_FLAG_ENCODE);\n        codec.start();\n    }\n\n    @Override\n    public void flow(byte[] bytes, int size) {\n        try {\n            ByteBuffer[] inputBuffers = codec.getInputBuffers();\n            ByteBuffer[] outputBuffers = codec.getOutputBuffers();\n            int inputBufferIndex = codec.dequeueInputBuffer(-1);\n            if (inputBufferIndex >= 0) {\n                ByteBuffer inputBuffer = inputBuffers[inputBufferIndex];\n                inputBuffer.clear();\n                inputBuffer.put(bytes);\n                codec.queueInputBuffer(inputBufferIndex, 0, size, 0, 0);\n            }\n\n            MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();\n            int outputBufferIndex = codec.dequeueOutputBuffer(bufferInfo, 0);\n\n            while (outputBufferIndex >= 0) {\n                ByteBuffer outputBuffer = outputBuffers[outputBufferIndex];\n                byte[] outData = new byte[bufferInfo.size];\n                outputBuffer.get(outData);\n                fos.write(outData, 0, outData.length);\n                LOG.d(\"FlacEncoder \" + outData.length + \" bytes written\");\n\n                codec.releaseOutputBuffer(outputBufferIndex, false);\n                outputBufferIndex = codec.dequeueOutputBuffer(bufferInfo, 0);\n\n            }\n        } catch (Throwable t) {\n            t.printStackTrace();\n        }\n    }\n\n    @Override\n    public boolean needExit() {\n        return false;\n    }\n\n    @Override\n    public void end() {\n        try {\n            if (codec != null) {\n                codec.stop();\n                codec.release();\n                codec = null;\n            }\n\n            if (fos != null) {\n                fos.flush();\n                fos.close();\n                fos = null;\n            }\n        } catch (Exception ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    public String getFilePath() {\n        return filePath;\n    }\n\n    @Override\n    public void release() {\n        end();\n    }\n\n}\n"
  },
  {
    "path": "demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/LocalScorerProcessor.java",
    "content": "package com.liulishuo.engzo.lingorecorder.demo;\n\nimport android.app.Application;\nimport android.content.ComponentName;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.ServiceConnection;\nimport android.os.Bundle;\nimport android.os.IBinder;\nimport android.os.RemoteException;\n\nimport com.liulishuo.engzo.IAudioProcessorService;\nimport com.liulishuo.engzo.lingorecorder.processor.AudioProcessor;\nimport com.liulishuo.engzo.lingorecorder.utils.LOG;\n\nimport java.util.concurrent.CountDownLatch;\n\n/**\n * Created by wcw on 4/14/17.\n */\n\npublic class LocalScorerProcessor implements AudioProcessor {\n\n    private boolean mBound = false;\n    private IAudioProcessorService scorerService;\n    private CountDownLatch countDownLatch;\n    private boolean hasRelease = false;\n    private Application application = null;\n    private String spokenText;\n    private int score;\n\n    public LocalScorerProcessor(Application  application, String spokenText) {\n        this.spokenText = spokenText;\n        this.application = application;\n    }\n\n    private ServiceConnection mConnection = new ServiceConnection() {\n        @Override\n        public void onServiceConnected(ComponentName name, IBinder service) {\n            mBound = true;\n            scorerService = IAudioProcessorService.Stub.asInterface(service);\n            countDownLatch.countDown();\n\n\n            // avoid ActivityManager: Scheduling restart of crashed service\n            if (hasRelease) {\n                application.unbindService(this);\n                mBound = false;\n            }\n            LOG.d(\"localScorer onServiceConnected\");\n        }\n\n        @Override\n        public void onServiceDisconnected(ComponentName name) {\n            mBound = false;\n            scorerService = null;\n            LOG.d(\"localScorer onServiceDisconnected\");\n        }\n    };\n\n    @Override\n    public void start() throws Exception {\n        countDownLatch = new CountDownLatch(1);\n        Intent intent = new Intent(application, ScorerService.class);\n        long startTime = System.currentTimeMillis();\n        application.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);\n        countDownLatch.await();\n        LOG.d(String.format(\"localScorer cost %dms to connect service\",\n                System.currentTimeMillis() - startTime));\n\n        Bundle bundle = new Bundle();\n        bundle.putString(\"spokenText\", spokenText);\n\n        scorerService.init(bundle);\n        scorerService.start();\n    }\n\n    @Override\n    public void flow(byte[] bytes, int size) throws Exception {\n        scorerService.flow(bytes, size);\n    }\n\n    @Override\n    public boolean needExit() {\n        try {\n            return scorerService.needExit();\n        } catch (RemoteException e) {\n            e.printStackTrace();\n            return true;\n        }\n    }\n\n    @Override\n    public void end() throws Exception {\n        scorerService.end();\n        score = scorerService.getResult().getInt(\"score\");\n    }\n\n    @Override\n    public void release() {\n        try {\n            hasRelease = true;\n            if (mBound) {\n                application.unbindService(mConnection);\n                mBound = false;\n            }\n        } catch (Exception ex) {\n            LOG.e(ex);\n        }\n    }\n\n    public int getScore() {\n        return score;\n    }\n}\n"
  },
  {
    "path": "demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/RecordPermissionHelper.java",
    "content": "package com.liulishuo.engzo.lingorecorder.demo;\n\nimport android.Manifest;\nimport android.content.DialogInterface;\nimport android.content.pm.PackageManager;\nimport android.os.Build;\nimport android.widget.Toast;\n\nimport androidx.appcompat.app.AlertDialog;\nimport androidx.appcompat.app.AppCompatActivity;\nimport androidx.core.content.PermissionChecker;\n\n/**\n * Created by rantianhua on 17/8/29.\n */\n\npublic class RecordPermissionHelper {\n\n    private static final int REQUEST_CODE_PERMISSION = 10010;\n\n    private final AppCompatActivity activity;\n\n    private PermissionGrantedListener grantedListener;\n\n    public RecordPermissionHelper(AppCompatActivity activity) {\n        this.activity = activity;\n    }\n\n    public void setGrantedListener(\n            PermissionGrantedListener grantedListener) {\n        this.grantedListener = grantedListener;\n    }\n\n    public boolean checkRecordPermission() {\n        if (PermissionChecker.checkSelfPermission(activity,\n                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PermissionChecker.PERMISSION_GRANTED\n                || PermissionChecker.checkSelfPermission(activity, Manifest.permission.RECORD_AUDIO)\n                != PermissionChecker.PERMISSION_GRANTED) {\n            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {\n                if (activity.shouldShowRequestPermissionRationale(\n                        Manifest.permission.WRITE_EXTERNAL_STORAGE) ||\n                        activity.shouldShowRequestPermissionRationale(\n                                Manifest.permission.RECORD_AUDIO)) {\n                    new AlertDialog.Builder(activity)\n                            .setTitle(R.string.check_permission_title)\n                            .setMessage(R.string.check_permission_content)\n                            .setCancelable(false)\n                            .setPositiveButton(R.string.confirm,\n                                    new DialogInterface.OnClickListener() {\n                                        @Override\n                                        public void onClick(DialogInterface dialog, int which) {\n                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {\n                                                activity.requestPermissions(new String[]{\n                                                                Manifest.permission\n                                                                        .WRITE_EXTERNAL_STORAGE,\n                                                                Manifest.permission.RECORD_AUDIO},\n                                                        REQUEST_CODE_PERMISSION);\n                                            }\n                                        }\n                                    }).show();\n                } else {\n                    activity.requestPermissions(\n                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,\n                                    Manifest.permission.RECORD_AUDIO}, REQUEST_CODE_PERMISSION);\n                }\n            }\n            return false;\n        }\n        return true;\n    }\n\n    public void onRequestPermissionsResult(int requestCode, String[] permissions,\n                                           int[] grantResults) {\n        if (requestCode == REQUEST_CODE_PERMISSION) {\n            for (int grantResult : grantResults) {\n                if (grantResult != PackageManager.PERMISSION_GRANTED) {\n                    Toast.makeText(activity, R.string.check_permission_fail,\n                            Toast.LENGTH_LONG).show();\n                    return;\n                }\n            }\n            if (grantedListener != null) {\n                grantedListener.onPermissionGranted();\n            }\n        }\n    }\n\n    public interface PermissionGrantedListener {\n        void onPermissionGranted();\n    }\n}\n"
  },
  {
    "path": "demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/ScorerService.java",
    "content": "package com.liulishuo.engzo.lingorecorder.demo;\n\nimport android.app.Service;\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.os.IBinder;\nimport android.os.RemoteException;\n\nimport androidx.annotation.Nullable;\n\nimport com.liulishuo.engzo.IAudioProcessorService;\n\nimport java.util.Random;\n\n/**\n * Created by wcw on 4/10/17.\n */\n\npublic class ScorerService extends Service {\n\n    private final IAudioProcessorService.Stub mBinder = new IAudioProcessorService.Stub() {\n\n        private Random random;\n        private Bundle resultBundle;\n\n        @Override\n        public void init(Bundle bundle) throws RemoteException {\n            resultBundle = new Bundle();\n        }\n\n        @Override\n        public void start() throws RemoteException {\n            random = new Random();\n        }\n\n        @Override\n        public void flow(byte[] bytes, int result) throws RemoteException {\n\n        }\n\n        @Override\n        public boolean needExit() throws RemoteException {\n            return false;\n        }\n\n        @Override\n        public void end() throws RemoteException {\n            resultBundle.putInt(\"score\", random.nextInt(100));\n        }\n\n        @Override\n        public void release() throws RemoteException {\n            random = null;\n        }\n\n        @Override\n        public Bundle getResult() throws RemoteException {\n            return resultBundle;\n        }\n    };\n\n    @Nullable\n    @Override\n    public IBinder onBind(Intent intent) {\n        return mBinder;\n    }\n\n\n}\n"
  },
  {
    "path": "demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/Utils.java",
    "content": "package com.liulishuo.engzo.lingorecorder.demo;\n\nimport android.annotation.TargetApi;\nimport android.media.MediaCodecInfo;\nimport android.media.MediaCodecList;\nimport android.os.Build;\n\nimport java.io.File;\nimport java.text.DecimalFormat;\n\n/**\n * Created by rantianhua on 17/8/29.\n */\n\npublic class Utils {\n\n\n    public static String getDurationString(long durationInMills) {\n        if (durationInMills < 1000) {\n            return durationInMills + \"ms\";\n        } else if (durationInMills < 1000 * 60) {\n            return (durationInMills / 1000) + \"s\";\n        } else {\n            return (durationInMills / 1000) + \"min\";\n        }\n    }\n\n    public static String formatFileSize(String path) {\n        File file = new File(path);\n        long size = file.length();\n        String[] units = {\"B\", \"kB\", \"MB\", \"GB\", \"TB\"};\n        if (size > 0) {\n            int digitGroups = (int) (Math.log10(size) / Math.log10(1024.0));\n            return new DecimalFormat(\"#,##0.#\").format(size / Math.pow(1024.0, digitGroups)) + \" \"\n                    + units[digitGroups];\n        } else {\n            return \"0B\";\n        }\n    }\n\n    public static MediaCodecInfo checkSupportMediaCodec(String mimeType) {\n        if (Build.VERSION.SDK_INT < 16) {\n            // TODO: 17/8/30 get codec list under api 16 https://stackoverflow\n            // .com/questions/19992479/how-to-get-the-codec-list-on-android-4-0\n            return null;\n        }\n        if (Build.VERSION.SDK_INT < 21) {\n            final int count = MediaCodecList.getCodecCount();\n            for (int i = 0; i < count; i++) {\n                MediaCodecInfo codecInfo = MediaCodecList.getCodecInfoAt(i);\n                if (!codecInfo.isEncoder()) {\n                    continue;\n                }\n                if (checkIsSpecifyCodec(mimeType, codecInfo)) {\n                    return codecInfo;\n                }\n            }\n            return null;\n        } else {\n            final MediaCodecList mediaCodecList = new MediaCodecList(MediaCodecList.REGULAR_CODECS);\n            for (MediaCodecInfo codecInfo : mediaCodecList.getCodecInfos()) {\n                if (checkIsSpecifyCodec(mimeType, codecInfo)) {\n                    return codecInfo;\n                }\n            }\n            return null;\n        }\n    }\n\n    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)\n    private static boolean checkIsSpecifyCodec(String mimeType, MediaCodecInfo mediaCodecInfo) {\n        String[] types = mediaCodecInfo.getSupportedTypes();\n        for (String type : types) {\n            if (type.equalsIgnoreCase(mimeType)) {\n                return true;\n            }\n        }\n        return false;\n    }\n}\n"
  },
  {
    "path": "demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/activity/AcrossProcessDemonstrateActivity.java",
    "content": "package com.liulishuo.engzo.lingorecorder.demo.activity;\n\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.TextView;\n\nimport com.liulishuo.engzo.lingorecorder.LingoRecorder;\nimport com.liulishuo.engzo.lingorecorder.demo.LocalScorerProcessor;\nimport com.liulishuo.engzo.lingorecorder.demo.R;\nimport com.liulishuo.engzo.lingorecorder.processor.AudioProcessor;\n\nimport java.util.Map;\n\n/**\n * demonstrate across process processor\n */\n\npublic class AcrossProcessDemonstrateActivity extends RecordActivity {\n\n    public static final String SCORER = \"localScorer\";\n\n    private Button btnScorer;\n    private TextView tvResult;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_across_process_demonstrate);\n\n        btnScorer = (Button) findViewById(R.id.btn_scorer);\n        tvResult = (TextView) findViewById(R.id.tv_scorer_result);\n        tvResult.setText(getString(R.string.scorer_result, \"\"));\n\n        btnScorer.setOnClickListener(new View.OnClickListener() {\n            @Override\n            public void onClick(View v) {\n                if (!checkRecordPermission()) return;\n                if (lingoRecorder.isRecording()) {\n                    lingoRecorder.stop();\n                } else if (!lingoRecorder.isProcessing()){\n                    lingoRecorder.start();\n                    tvResult.setText(getString(R.string.scorer_result, \"\"));\n                    btnScorer.setText(R.string.stop_scorer);\n                }\n            }\n        });\n\n        final String spokenText = getString(R.string.scorer_sentence);\n        lingoRecorder.put(SCORER, new LocalScorerProcessor(getApplication(), spokenText));\n    }\n\n    @Override\n    protected void onProcessError(Throwable throwable) {\n        super.onProcessError(throwable);\n        btnScorer.setText(R.string.start_record);\n    }\n\n    @Override\n    protected void onRecordError(Throwable throwable) {\n        super.onRecordError(throwable);\n        btnScorer.setText(R.string.start_record);\n    }\n\n    @Override\n    protected void onProcessStop(Map<String, AudioProcessor> map) {\n        btnScorer.setText(R.string.start_record);\n        LocalScorerProcessor localScorerProcessor = (LocalScorerProcessor) map.get(SCORER);\n        tvResult.setText(\n                getString(R.string.scorer_result, String.valueOf(localScorerProcessor.getScore())));\n    }\n\n    @Override\n    protected void onRecordStop(LingoRecorder.OnRecordStopListener.Result result) {\n\n    }\n\n    @Override\n    protected void onPermissionGranted() {\n        btnScorer.performClick();\n    }\n}\n"
  },
  {
    "path": "demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/activity/DemoListActivity.java",
    "content": "package com.liulishuo.engzo.lingorecorder.demo.activity;\n\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.view.View;\n\nimport androidx.annotation.Nullable;\nimport androidx.appcompat.app.AppCompatActivity;\n\nimport com.liulishuo.engzo.lingorecorder.demo.R;\n\n/**\n * Created by rantianhua on 17/8/29.\n * show demo list\n */\n\npublic class DemoListActivity extends AppCompatActivity {\n\n    @Override\n    protected void onCreate(@Nullable Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_demo_list);\n    }\n\n    public void recordDemonstrate(View view) {\n        startActivity(new Intent(this, RecordDemonstrateActivity.class));\n    }\n\n    public void processorsDemonstrate(View view) {\n        startActivity(new Intent(this, ProcessorsDemonstrateActivity.class));\n    }\n\n    public void flacDemonstrate(View view) {\n        startActivity(new Intent(this, FlacDemonstrateActivity.class));\n    }\n\n    public void acrossProcessDemonstrate(View view) {\n        startActivity(new Intent(this, AcrossProcessDemonstrateActivity.class));\n    }\n\n    public void volumeDemonstrate(View view) {\n        startActivity(new Intent(this, VolumeDemonstrateActivity.class));\n    }\n\n}\n"
  },
  {
    "path": "demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/activity/FlacDemonstrateActivity.java",
    "content": "package com.liulishuo.engzo.lingorecorder.demo.activity;\n\nimport android.annotation.TargetApi;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.TextView;\n\nimport com.liulishuo.engzo.lingorecorder.LingoRecorder;\nimport com.liulishuo.engzo.lingorecorder.demo.AndroidFlacProcessor;\nimport com.liulishuo.engzo.lingorecorder.demo.R;\nimport com.liulishuo.engzo.lingorecorder.demo.Utils;\nimport com.liulishuo.engzo.lingorecorder.processor.AudioProcessor;\n\nimport java.util.Map;\n\n/**\n * demonstrate flac codec\n */\n\npublic class FlacDemonstrateActivity extends RecordActivity {\n\n    private static final String FLAC = \"androidFlac\";\n\n    private Button btnRecord;\n    private EditText etOutput;\n    private TextView tvDuration;\n    private TextView tvSize;\n\n    private AndroidFlacProcessor flacProcessor;\n    private String outputFile;\n\n    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_flac_demonstrate);\n\n        tvDuration = (TextView) findViewById(R.id.record_duration);\n        tvSize = (TextView) findViewById(R.id.record_size);\n        tvDuration.setText(getString(R.string.record_duration, \"\"));\n        tvSize.setText(getString(R.string.record_size, \"\"));\n\n        etOutput = (EditText) findViewById(R.id.et_output_file);\n        View unSupportView = findViewById(R.id.tv_unsuport_view);\n        View demonstrateView = findViewById(R.id.view_demonstrate);\n\n        final boolean supportFlac = checkSupportFlac();\n        if (!supportFlac) {\n            unSupportView.setVisibility(View.VISIBLE);\n            demonstrateView.setVisibility(View.GONE);\n            return;\n        }\n        unSupportView.setVisibility(View.GONE);\n        demonstrateView.setVisibility(View.VISIBLE);\n\n        flacProcessor = new AndroidFlacProcessor();\n        lingoRecorder.put(FLAC, flacProcessor);\n\n        btnRecord = (Button) findViewById(R.id.btn_record);\n        btnRecord.setOnClickListener(new View.OnClickListener() {\n            @Override\n            public void onClick(View v) {\n                if (!checkRecordPermission()) return;\n                if (lingoRecorder.isRecording()) {\n                    lingoRecorder.stop();\n                } else if (!lingoRecorder.isProcessing()){\n                    outputFile = etOutput.getText().toString();\n                    flacProcessor.setFilePath(outputFile);\n                    lingoRecorder.start();\n                    btnRecord.setText(R.string.stop_record);\n                }\n            }\n        });\n    }\n\n    private boolean checkSupportFlac() {\n        return Utils.checkSupportMediaCodec(\"audio/flac\") != null;\n    }\n\n    @Override\n    protected void onRecordError(Throwable throwable) {\n        super.onRecordError(throwable);\n        btnRecord.setText(R.string.start_record);\n    }\n\n    @Override\n    protected void onProcessError(Throwable throwable) {\n        super.onProcessError(throwable);\n        btnRecord.setText(R.string.start_record);\n    }\n\n    @Override\n    protected void onProcessStop(Map<String, AudioProcessor> map) {\n        btnRecord.setText(R.string.start_record);\n        tvSize.setText(getString(R.string.record_size, Utils.formatFileSize(outputFile)));\n    }\n\n    @Override\n    protected void onRecordStop(LingoRecorder.OnRecordStopListener.Result result) {\n        tvDuration.setText(getString(R.string.record_duration,\n                Utils.getDurationString(result.getDurationInMills())));\n    }\n\n    @Override\n    protected void onPermissionGranted() {\n        btnRecord.performClick();\n    }\n}\n"
  },
  {
    "path": "demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/activity/ProcessorsDemonstrateActivity.java",
    "content": "package com.liulishuo.engzo.lingorecorder.demo.activity;\n\nimport android.content.Context;\nimport android.graphics.Color;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.Message;\nimport android.util.TypedValue;\nimport android.view.Gravity;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.Button;\nimport android.widget.TextView;\n\nimport androidx.annotation.Nullable;\nimport androidx.recyclerview.widget.LinearLayoutManager;\nimport androidx.recyclerview.widget.RecyclerView;\n\nimport com.liulishuo.engzo.lingorecorder.LingoRecorder;\nimport com.liulishuo.engzo.lingorecorder.demo.R;\nimport com.liulishuo.engzo.lingorecorder.processor.AudioProcessor;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Map;\n\n/**\n * Created by rantianhua on 17/8/29.\n * demonstrate how to custom processor for record data\n */\n\npublic class ProcessorsDemonstrateActivity extends RecordActivity {\n\n    private static final String PROCESSOR_1 = \"processor1\";\n    private static final String PROCESSOR_2 = \"processor2\";\n\n    private TextView tvProcessor1;\n    private TextView tvProcessor2;\n    private RecyclerView rcv1;\n    private RecyclerView rcv2;\n    private Button btn;\n\n    private Handler handler;\n\n    private ProcessorAdapter adapter1;\n    private ProcessorAdapter adapter2;\n\n    @Override\n    protected void onCreate(@Nullable Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_processors_demonstrate);\n\n        tvProcessor1 = (TextView) findViewById(R.id.tv_processor_1_title);\n        tvProcessor2 = (TextView) findViewById(R.id.tv_processor_2_title);\n        tvProcessor1.setText(getString(R.string.processor_1_title, \"\"));\n        tvProcessor2.setText(getString(R.string.processor_2_title, \"\"));\n\n        rcv1 = (RecyclerView) findViewById(R.id.rcv_processor_1);\n        rcv2 = (RecyclerView) findViewById(R.id.rcv_processor_2);\n        adapter1 = new ProcessorAdapter();\n        adapter2 = new ProcessorAdapter();\n        rcv1.setLayoutManager(new LinearLayoutManager(this));\n        rcv1.setHasFixedSize(true);\n        rcv1.setAdapter(adapter1);\n        rcv2.setLayoutManager(new LinearLayoutManager(this));\n        rcv2.setHasFixedSize(true);\n        rcv2.setAdapter(adapter2);\n\n        btn = (Button) findViewById(R.id.btn_record);\n        btn.setOnClickListener(new View.OnClickListener() {\n            @Override\n            public void onClick(View v) {\n                if (!checkRecordPermission()) return;\n                if (lingoRecorder.isRecording()) {\n                    lingoRecorder.stop();\n                } else if (!lingoRecorder.isProcessing()){\n                    lingoRecorder.start();\n                    btn.setText(R.string.stop_record);\n                }\n            }\n        });\n\n        initHandler();\n\n        initLingoRecorder();\n    }\n\n    private void initHandler() {\n        handler = new Handler(new Handler.Callback() {\n            @Override\n            public boolean handleMessage(Message msg) {\n                if (isFinishing()) return false;\n                final String data = (String) msg.obj;\n                if (msg.what == 1) {\n                    adapter1.addData(data);\n                    rcv1.scrollToPosition(adapter1.getItemCount() - 1);\n                } else if (msg.what == 2) {\n                    adapter2.addData(data);\n                    rcv2.scrollToPosition(adapter2.getItemCount() - 1);\n                }\n                return false;\n            }\n        });\n    }\n\n    private void initLingoRecorder() {\n        lingoRecorder.put(PROCESSOR_1, new\n\n                AudioProcessor() {\n\n                    private int item;\n\n                    @Override\n                    public void start() throws Exception {\n                        handler.post(new Runnable() {\n                            @Override\n                            public void run() {\n                                tvProcessor1.setText(\n                                        getString(R.string.processor_1_title, \"start\"));\n                            }\n                        });\n                    }\n\n                    @Override\n                    public void flow(byte[] bytes, int size) throws Exception {\n                        final Message message = handler.obtainMessage();\n                        message.what = 1;\n                        message.obj = String.format(Locale.CHINA,\n                                \"handle flow item, position at %d, size is %d\", (++item), size);\n                        handler.sendMessage(message);\n                        if (item == 1) {\n                            handler.post(new Runnable() {\n                                @Override\n                                public void run() {\n                                    tvProcessor1.setText(\n                                            getString(R.string.processor_1_title, \"processing...\"));\n                                }\n                            });\n                        }\n                    }\n\n                    @Override\n                    public boolean needExit() {\n                        return false;\n                    }\n\n                    @Override\n                    public void end() throws Exception {\n                        handler.post(new Runnable() {\n                            @Override\n                            public void run() {\n                                tvProcessor1.setText(getString(R.string.processor_1_title, \"stop\"));\n                            }\n                        });\n                    }\n\n                    @Override\n                    public void release() {\n                        item = 0;\n                    }\n                });\n        lingoRecorder.put(PROCESSOR_2, new\n\n                AudioProcessor() {\n\n                    private int item;\n\n                    @Override\n                    public void start() throws Exception {\n                        handler.post(new Runnable() {\n                            @Override\n                            public void run() {\n                                tvProcessor2.setText(\n                                        getString(R.string.processor_2_title, \"start\"));\n                            }\n                        });\n                    }\n\n                    @Override\n                    public void flow(byte[] bytes, int size) throws Exception {\n                        final Message message = handler.obtainMessage();\n                        message.what = 2;\n                        message.obj = String.format(Locale.CHINA,\n                                \"handle flow item, position at %d, size is %d\", (++item), size);\n                        handler.sendMessage(message);\n                        if (item == 1) {\n                            handler.post(new Runnable() {\n                                @Override\n                                public void run() {\n                                    tvProcessor2.setText(\n                                            getString(R.string.processor_2_title, \"processing...\"));\n                                }\n                            });\n                        }\n                    }\n\n                    @Override\n                    public boolean needExit() {\n                        return false;\n                    }\n\n                    @Override\n                    public void end() throws Exception {\n                        handler.post(new Runnable() {\n                            @Override\n                            public void run() {\n                                tvProcessor2.setText(getString(R.string.processor_2_title, \"stop\"));\n                            }\n                        });\n                    }\n\n                    @Override\n                    public void release() {\n                        item = 0;\n                    }\n                });\n    }\n\n    @Override\n    protected void onProcessStop(Map<String, AudioProcessor> map) {\n        btn.setText(R.string.start_record);\n    }\n\n    @Override\n    protected void onRecordStop(LingoRecorder.OnRecordStopListener.Result result) {\n\n    }\n\n    @Override\n    protected void onPermissionGranted() {\n        btn.performClick();\n    }\n\n    static class ProcessorAdapter extends RecyclerView.Adapter<ProcessorAdapter.VH> {\n\n        private final List<String> data;\n\n        ProcessorAdapter() {\n            this.data = new ArrayList<>();\n        }\n\n        @Override\n        public VH onCreateViewHolder(ViewGroup parent,\n                int viewType) {\n            final TextView textView = new TextView(parent.getContext());\n            textView.setTextColor(Color.BLACK);\n            textView.setPadding(0, dpToPx(parent.getContext(), 5), 0,\n                    dpToPx(parent.getContext(), 5));\n            textView.setGravity(Gravity.START | Gravity.CENTER_VERTICAL);\n            return new VH(textView);\n        }\n\n        int dpToPx(Context context, int dp) {\n            return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,\n                    context.getResources().getDisplayMetrics());\n        }\n\n        @Override\n        public void onBindViewHolder(VH holder,\n                int position) {\n            holder.tv.setText(data.get(position));\n        }\n\n        @Override\n        public int getItemCount() {\n            return data.size();\n        }\n\n        void addData(String item) {\n            if (data.size() > 20) {\n                data.remove(0);\n            }\n            data.add(item);\n            notifyDataSetChanged();\n        }\n\n        static class VH extends RecyclerView.ViewHolder {\n\n            TextView tv;\n\n            VH(View itemView) {\n                super(itemView);\n                tv = (TextView) itemView;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/activity/RecordActivity.java",
    "content": "package com.liulishuo.engzo.lingorecorder.demo.activity;\n\nimport android.os.Bundle;\nimport android.util.Log;\nimport android.widget.Toast;\n\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.appcompat.app.AppCompatActivity;\n\nimport com.liulishuo.engzo.lingorecorder.LingoRecorder;\nimport com.liulishuo.engzo.lingorecorder.demo.R;\nimport com.liulishuo.engzo.lingorecorder.demo.RecordPermissionHelper;\nimport com.liulishuo.engzo.lingorecorder.processor.AudioProcessor;\n\nimport java.util.Map;\n\n/**\n * Created by rantianhua on 17/8/29.\n */\n\npublic abstract class RecordActivity extends AppCompatActivity {\n\n    private static final String TAG = \"LingoRecorder\";\n\n    protected RecordPermissionHelper recordPermissionHelper;\n    protected LingoRecorder lingoRecorder;\n\n    @Override\n    protected void onCreate(@Nullable Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        recordPermissionHelper = new RecordPermissionHelper(this);\n        recordPermissionHelper.setGrantedListener(\n                new RecordPermissionHelper.PermissionGrantedListener() {\n                    @Override\n                    public void onPermissionGranted() {\n                        RecordActivity.this.onPermissionGranted();\n                    }\n                });\n        lingoRecorder = new LingoRecorder();\n        lingoRecorder.setOnRecordStopListener(new LingoRecorder.OnRecordStopListener() {\n            @Override\n            public void onRecordStop(Throwable throwable,\n                    Result result) {\n                if (throwable != null) {\n                    RecordActivity.this.onRecordError(throwable);\n                } else {\n                    RecordActivity.this.onRecordStop(result);\n                }\n            }\n        });\n        lingoRecorder.setOnProcessStopListener(new LingoRecorder.OnProcessStopListener() {\n            @Override\n            public void onProcessStop(Throwable throwable, Map<String, AudioProcessor> map) {\n                if (throwable != null) {\n                    RecordActivity.this.onProcessError(throwable);\n                } else {\n                    RecordActivity.this.onProcessStop(map);\n                }\n            }\n        });\n    }\n\n    protected void onProcessError(Throwable throwable) {\n        Toast.makeText(this, getString(R.string.process_failed), Toast.LENGTH_SHORT).show();\n        Log.e(TAG, \"Error in processor: \\n\" + Log.getStackTraceString(throwable), throwable);\n    }\n\n    protected void onRecordError(Throwable throwable) {\n        Toast.makeText(this, getString(R.string.record_failed), Toast.LENGTH_SHORT).show();\n        Log.e(TAG, \"Error in recorder: \\n\" + Log.getStackTraceString(throwable), throwable);\n    }\n\n    @Override\n    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,\n            @NonNull int[] grantResults) {\n        super.onRequestPermissionsResult(requestCode, permissions, grantResults);\n        recordPermissionHelper.onRequestPermissionsResult(requestCode, permissions, grantResults);\n    }\n\n    protected boolean checkRecordPermission() {\n        return recordPermissionHelper.checkRecordPermission();\n    }\n\n    @Override\n    protected void onDestroy() {\n        super.onDestroy();\n        if (lingoRecorder.isRecording()) {\n            lingoRecorder.cancel();\n        }\n    }\n\n    protected abstract void onProcessStop(Map<String, AudioProcessor> map);\n\n    protected abstract void onRecordStop(LingoRecorder.OnRecordStopListener.Result result);\n\n    protected abstract void onPermissionGranted();\n}\n"
  },
  {
    "path": "demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/activity/RecordDemonstrateActivity.java",
    "content": "package com.liulishuo.engzo.lingorecorder.demo.activity;\n\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.util.Log;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.TextView;\n\nimport androidx.annotation.Nullable;\nimport androidx.core.content.FileProvider;\n\nimport com.liulishuo.engzo.lingorecorder.LingoRecorder;\nimport com.liulishuo.engzo.lingorecorder.demo.BuildConfig;\nimport com.liulishuo.engzo.lingorecorder.demo.R;\nimport com.liulishuo.engzo.lingorecorder.demo.Utils;\nimport com.liulishuo.engzo.lingorecorder.processor.AudioProcessor;\nimport com.liulishuo.engzo.lingorecorder.volume.OnVolumeListener;\n\nimport java.io.File;\nimport java.util.Map;\n\n/**\n * Created by rantianhua on 17/8/29.\n * demonstrate how to record with {@link LingoRecorder}\n */\n\npublic class RecordDemonstrateActivity extends RecordActivity {\n\n    private Button btnRecord;\n    private Button btnPlay;\n    private TextView tvRecordDuration;\n    private TextView tvRecordSize;\n    private EditText etOutputFile;\n\n    private String outputFile;\n\n\n    @Override\n    protected void onCreate(@Nullable Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_record_demonstrate);\n\n        btnRecord = (Button) findViewById(R.id.btn_record);\n        btnPlay = (Button) findViewById(R.id.btn_play);\n        tvRecordDuration = (TextView) findViewById(R.id.record_duration);\n        tvRecordSize = (TextView) findViewById(R.id.record_size);\n        etOutputFile = (EditText) findViewById(R.id.et_output_file);\n\n        tvRecordDuration.setText(getString(R.string.record_duration, \"\"));\n        tvRecordSize.setText(getString(R.string.record_size, \"\"));\n\n        btnRecord.setOnClickListener(new View.OnClickListener() {\n            @Override\n            public void onClick(View v) {\n                if (!checkRecordPermission()) return;\n                handleRecorderBtn();\n            }\n        });\n\n        btnPlay.setOnClickListener(new View.OnClickListener() {\n            @Override\n            public void onClick(View v) {\n                Intent intent = new Intent();\n                intent.setAction(Intent.ACTION_VIEW);\n                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {\n                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);\n                    Uri contentUri = FileProvider.getUriForFile(\n                            getApplicationContext(),\n                            BuildConfig.APPLICATION_ID + \".fileProvider\",\n                            new File(outputFile));\n                    intent.setDataAndType(contentUri, \"audio/*\");\n                } else {\n                    intent.setDataAndType(Uri.parse(\"file://\" + outputFile), \"audio/*\");\n                }\n                startActivity(intent);\n            }\n        });\n\n        lingoRecorder.setOnVolumeListener(new OnVolumeListener() {\n            @Override\n            public void onVolume(double volume) {\n                Log.d(RecordDemonstrateActivity.class.getSimpleName(), \"volume is \" + volume);\n            }\n        });\n    }\n\n    private void handleRecorderBtn() {\n        if (lingoRecorder.isRecording()) {\n            lingoRecorder.stop();\n        } else if (!lingoRecorder.isProcessing()) {\n            lingoRecorder.start(etOutputFile.getText().toString());\n            btnRecord.setText(R.string.stop_record);\n            btnPlay.setEnabled(false);\n        }\n    }\n\n    @Override\n    protected void onRecordError(Throwable throwable) {\n        super.onRecordError(throwable);\n        btnRecord.setText(R.string.start_record);\n    }\n\n    @Override\n    protected void onProcessError(Throwable throwable) {\n        super.onProcessError(throwable);\n        btnRecord.setText(R.string.start_record);\n    }\n\n    @Override\n    protected void onProcessStop(Map<String, AudioProcessor> map) {\n        btnRecord.setText(R.string.start_record);\n        btnPlay.setEnabled(true);\n        tvRecordSize.setText(getString(R.string.record_size, Utils.formatFileSize(outputFile)));\n    }\n\n    @Override\n    protected void onRecordStop(LingoRecorder.OnRecordStopListener.Result result) {\n        outputFile = result.getOutputFilePath();\n        tvRecordDuration.setText(getString(R.string.record_duration,\n                Utils.getDurationString(result.getDurationInMills())));\n    }\n\n    @Override\n    protected void onPermissionGranted() {\n        btnRecord.performClick();\n    }\n\n\n}\n"
  },
  {
    "path": "demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/activity/VolumeDemonstrateActivity.java",
    "content": "package com.liulishuo.engzo.lingorecorder.demo.activity;\n\nimport android.os.Bundle;\nimport android.util.Log;\nimport android.view.View;\nimport android.widget.Button;\n\nimport androidx.annotation.Nullable;\n\nimport com.liulishuo.engzo.lingorecorder.LingoRecorder;\nimport com.liulishuo.engzo.lingorecorder.demo.R;\nimport com.liulishuo.engzo.lingorecorder.demo.view.VolumeView;\nimport com.liulishuo.engzo.lingorecorder.processor.AudioProcessor;\nimport com.liulishuo.engzo.lingorecorder.volume.OnVolumeListener;\n\nimport java.util.Map;\n\n/**\n * Created by rantianhua on 2017/9/26.\n * demonstrate the volume value during recording\n */\n\npublic class VolumeDemonstrateActivity extends RecordActivity {\n\n    private Button btnRecord;\n    private VolumeView volumeView;\n    private double maxVolume = 90;\n\n    @Override\n    protected void onCreate(@Nullable Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_volume);\n\n        volumeView = (VolumeView) findViewById(R.id.volume_view);\n        btnRecord = (Button) findViewById(R.id.btn_record);\n        btnRecord.setOnClickListener(new View.OnClickListener() {\n            @Override\n            public void onClick(View v) {\n                if (!checkRecordPermission()) return;\n                handleRecorderBtn();\n            }\n        });\n\n        lingoRecorder.setOnVolumeListener(new OnVolumeListener() {\n            @Override\n            public void onVolume(double volume) {\n                double rate = volume / maxVolume;\n                //more sensitive to volume change\n                Log.d(\"VolumeDemonstrate\", \"rate is \" + rate);\n                rate = rate * rate * rate;\n                volumeView.setAmplitude(rate);\n            }\n        });\n\n        lingoRecorder.setDebugEnable(true);\n    }\n\n    private void handleRecorderBtn() {\n        if (lingoRecorder.isRecording()) {\n            lingoRecorder.stop();\n        } else if (!lingoRecorder.isProcessing()){\n            lingoRecorder.start();\n            volumeView.startWave();\n            btnRecord.setText(R.string.stop_record);\n        }\n    }\n\n    @Override\n    protected void onRecordError(Throwable throwable) {\n        super.onRecordError(throwable);\n        btnRecord.setText(R.string.start_record);\n    }\n\n    @Override\n    protected void onProcessError(Throwable throwable) {\n        super.onProcessError(throwable);\n        btnRecord.setText(R.string.start_record);\n    }\n\n    @Override\n    protected void onProcessStop(Map<String, AudioProcessor> map) {\n        btnRecord.setText(R.string.start_record);\n    }\n\n    @Override\n    protected void onRecordStop(LingoRecorder.OnRecordStopListener.Result result) {\n        volumeView.stopWave();\n    }\n\n    @Override\n    protected void onPermissionGranted() {\n        btnRecord.performClick();\n    }\n}\n"
  },
  {
    "path": "demo/src/main/java/com/liulishuo/engzo/lingorecorder/demo/view/VolumeView.java",
    "content": "package com.liulishuo.engzo.lingorecorder.demo.view;\n\nimport android.content.Context;\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.graphics.Path;\nimport android.os.Build;\nimport android.os.Handler;\nimport android.util.AttributeSet;\nimport android.view.View;\n\nimport androidx.annotation.Nullable;\nimport androidx.annotation.RequiresApi;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Created by rantianhua on 2017/9/27.\n * show the change of volume\n */\n\npublic class VolumeView extends View {\n\n    private Path path;\n    private double amplitude;\n    private int step = 3;\n    private Paint paint;\n    private Handler handler;\n    private Runnable waveRunnable;\n    private long startTime;\n    private List<Float> xCalculateSamples;\n    private List<Integer> originX;\n\n    public VolumeView(Context context) {\n        super(context);\n        init();\n    }\n\n    public VolumeView(Context context, @Nullable AttributeSet attrs) {\n        super(context, attrs);\n        init();\n    }\n\n    public VolumeView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {\n        super(context, attrs, defStyleAttr);\n        init();\n    }\n\n    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)\n    public VolumeView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {\n        super(context, attrs, defStyleAttr, defStyleRes);\n        init();\n    }\n\n    private void init() {\n        paint = new Paint();\n        paint.setStrokeWidth(5);\n        paint.setAntiAlias(true);\n        paint.setStyle(Paint.Style.STROKE);\n        paint.setColor(Color.GREEN);\n        path = new Path();\n\n        handler = new Handler();\n        waveRunnable = new Runnable() {\n            @Override\n            public void run() {\n                invalidate();\n                startWave();\n            }\n        };\n    }\n\n    @Override\n    protected void onDraw(Canvas canvas) {\n        final int width = getWidth();\n        final int height = getHeight();\n\n        path.reset();\n        if (xCalculateSamples == null) {\n            calculateSample(width);\n        }\n        final int ampl = (int) (amplitude * (height / 2));\n        final float offset = ((System.currentTimeMillis() - startTime) / 200f) % 2;\n\n        path.moveTo(originX.get(0), height / 2);\n        for (int i = 0; i < xCalculateSamples.size(); i++) {\n            final float x = originX.get(i);\n            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);\n            path.lineTo(x, y + height / 2);\n        }\n\n        canvas.drawPath(path, paint);\n    }\n\n    private void calculateSample(int width) {\n        xCalculateSamples = new ArrayList<>();\n        originX = new ArrayList<>();\n        for (int i = 0; i <= width; i += step) {\n            xCalculateSamples.add((i / (float) width) * 4 - 2);\n            originX.add(i);\n        }\n    }\n\n    public void setAmplitude(double amplitude) {\n        this.amplitude = amplitude;\n    }\n\n    public void startWave() {\n        if (startTime == 0) {\n            startTime = System.currentTimeMillis();\n        }\n        handler.postDelayed(waveRunnable, 16);\n    }\n\n    public void stopWave() {\n        handler.removeCallbacks(waveRunnable);\n        setAmplitude(0);\n        invalidate();\n    }\n\n    @Override\n    protected void onDetachedFromWindow() {\n        stopWave();\n        super.onDetachedFromWindow();\n    }\n}\n"
  },
  {
    "path": "demo/src/main/res/layout/activity_across_process_demonstrate.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout\n\txmlns:android=\"http://schemas.android.com/apk/res/android\"\n\txmlns:tools=\"http://schemas.android.com/tools\"\n\tandroid:layout_width=\"match_parent\"\n\tandroid:layout_height=\"match_parent\"\n\ttools:context=\"com.liulishuo.engzo.lingorecorder.demo.activity.AcrossProcessDemonstrateActivity\"\n\tandroid:orientation=\"vertical\">\n\t\n\t<TextView\n\t\tandroid:layout_width=\"wrap_content\"\n\t\tandroid:layout_height=\"wrap_content\"\n\t\tandroid:text=\"@string/please_read\"\n\t\tandroid:layout_marginTop=\"20dp\"\n\t\tandroid:layout_marginLeft=\"20dp\"\n\t\tandroid:layout_marginStart=\"20dp\"\n\t/>\n\t\n\t<TextView\n\t\tandroid:layout_width=\"wrap_content\"\n\t\tandroid:layout_height=\"wrap_content\"\n\t\tandroid:text=\"@string/scorer_sentence\"\n\t\tandroid:textColor=\"@android:color/black\"\n\t\tandroid:layout_marginTop=\"20dp\"\n\t\tandroid:layout_marginLeft=\"20dp\"\n\t\tandroid:layout_marginStart=\"20dp\"\n\t/>\n\t\n\t<Button\n\t\tandroid:layout_width=\"match_parent\"\n\t\tandroid:layout_height=\"wrap_content\"\n\t\tandroid:layout_marginTop=\"20dp\"\n\t\tandroid:layout_marginLeft=\"20dp\"\n\t\tandroid:layout_marginStart=\"20dp\"\n\t\tandroid:layout_marginRight=\"20dp\"\n\t\tandroid:layout_marginEnd=\"20dp\"\n\t\tandroid:textAllCaps=\"false\"\n\t\tandroid:text=\"@string/start_scorer\"\n\t\tandroid:id=\"@+id/btn_scorer\"\n\t/>\n\t\n\t<TextView\n\t\tandroid:layout_width=\"wrap_content\"\n\t\tandroid:layout_height=\"wrap_content\"\n\t\tandroid:text=\"@string/scorer_result\"\n\t\tandroid:textColor=\"@android:color/black\"\n\t\tandroid:layout_marginTop=\"20dp\"\n\t\tandroid:layout_marginLeft=\"20dp\"\n\t\tandroid:layout_marginStart=\"20dp\"\n\t\tandroid:id=\"@+id/tv_scorer_result\"\n\t/>\n\n</LinearLayout>\n"
  },
  {
    "path": "demo/src/main/res/layout/activity_demo_list.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n                xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\"\n                android:layout_height=\"match_parent\"\n>\n\t\n\t<LinearLayout\n\t\tandroid:layout_width=\"match_parent\"\n\t\tandroid:layout_height=\"wrap_content\"\n\t\tandroid:orientation=\"vertical\"\n\t\tandroid:layout_centerVertical=\"true\"\n\t\ttools:ignore=\"UselessParent\">\n\t\t\n\t\t<Button\n\t\t\tandroid:layout_width=\"200dp\"\n\t\t\tandroid:layout_height=\"45dp\"\n\t\t\tandroid:text=\"@string/record_demonstrate\"\n\t\t\tandroid:textAllCaps=\"false\"\n\t\t\tandroid:onClick=\"recordDemonstrate\"\n\t\t\tandroid:layout_gravity=\"center_horizontal\"/>\n\t\t\n\t\t<Button\n\t\t\tandroid:layout_width=\"200dp\"\n\t\t\tandroid:layout_height=\"45dp\"\n\t\t\tandroid:text=\"@string/custom_processors_demonstrate\"\n\t\t\tandroid:textAllCaps=\"false\"\n\t\t\tandroid:layout_gravity=\"center_horizontal\"\n\t\t\tandroid:onClick=\"processorsDemonstrate\"\n\t\t\tandroid:layout_marginTop=\"20dp\"/>\n\t\t\n\t\t<Button\n\t\t\tandroid:layout_width=\"200dp\"\n\t\t\tandroid:layout_height=\"45dp\"\n\t\t\tandroid:text=\"@string/flac_demonstrate\"\n\t\t\tandroid:textAllCaps=\"false\"\n\t\t\tandroid:layout_gravity=\"center_horizontal\"\n\t\t\tandroid:layout_marginTop=\"20dp\"\n\t\t\tandroid:onClick=\"flacDemonstrate\"/>\n\t\t\n\t\t<Button\n\t\t\tandroid:layout_width=\"200dp\"\n\t\t\tandroid:layout_height=\"45dp\"\n\t\t\tandroid:text=\"@string/across_process_processor_demonstrate\"\n\t\t\tandroid:textAllCaps=\"false\"\n\t\t\tandroid:id=\"@+id/btn_flac_sample\"\n\t\t\tandroid:layout_gravity=\"center_horizontal\"\n\t\t\tandroid:layout_marginTop=\"20dp\"\n\t\t\tandroid:onClick=\"acrossProcessDemonstrate\"/>\n\n\t\t<Button\n\t\t\tandroid:layout_width=\"200dp\"\n\t\t\tandroid:layout_height=\"45dp\"\n\t\t\tandroid:text=\"@string/volume_demonstrate\"\n\t\t\tandroid:textAllCaps=\"false\"\n\t\t\tandroid:id=\"@+id/btn_volume_sample\"\n\t\t\tandroid:layout_gravity=\"center_horizontal\"\n\t\t\tandroid:layout_marginTop=\"20dp\"\n\t\t\tandroid:onClick=\"volumeDemonstrate\" />\n\t\n\t</LinearLayout>\n\n</RelativeLayout>"
  },
  {
    "path": "demo/src/main/res/layout/activity_flac_demonstrate.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout\n\txmlns:android=\"http://schemas.android.com/apk/res/android\"\n\txmlns:tools=\"http://schemas.android.com/tools\"\n\tandroid:layout_width=\"match_parent\"\n\tandroid:layout_height=\"match_parent\"\n\tandroid:orientation=\"vertical\"\n\ttools:context=\"com.liulishuo.engzo.lingorecorder.demo.activity.FlacDemonstrateActivity\">\n\t\n\t<TextView\n\t\tandroid:layout_width=\"match_parent\"\n\t\tandroid:layout_height=\"match_parent\"\n\t\tandroid:id=\"@+id/tv_unsuport_view\"\n\t\tandroid:text=\"@string/flac_unsupport\"\n\t\tandroid:gravity=\"center\"\n\t\tandroid:textColor=\"@android:color/black\"\n\t\ttools:visibility=\"gone\"/>\n\t\n\t<LinearLayout\n\t\tandroid:layout_width=\"match_parent\"\n\t\tandroid:layout_height=\"match_parent\"\n\t\tandroid:id=\"@+id/view_demonstrate\"\n\t\tandroid:orientation=\"vertical\">\n\t\t\n\t\t<TextView\n\t\t\tandroid:layout_width=\"wrap_content\"\n\t\t\tandroid:layout_height=\"wrap_content\"\n\t\t\tandroid:text=\"@string/record_output_address\"\n\t\t\tandroid:layout_marginTop=\"20dp\"\n\t\t\tandroid:layout_marginLeft=\"20dp\"\n\t\t\tandroid:layout_marginStart=\"20dp\"\n\t\t/>\n\t\t\n\t\t<EditText\n\t\t\tandroid:layout_width=\"match_parent\"\n\t\t\tandroid:layout_height=\"wrap_content\"\n\t\t\tandroid:id=\"@+id/et_output_file\"\n\t\t\tandroid:inputType=\"text\"\n\t\t\tandroid:textColor=\"@android:color/black\"\n\t\t\tandroid:text=\"@string/sdcard_test_flac\"\n\t\t\tandroid:layout_marginLeft=\"20dp\"\n\t\t\tandroid:layout_marginStart=\"20dp\"\n\t\t\tandroid:layout_marginTop=\"10dp\"/>\n\t\t\n\t\t<Button\n\t\t\tandroid:layout_width=\"match_parent\"\n\t\t\tandroid:layout_height=\"wrap_content\"\n\t\t\tandroid:layout_marginTop=\"20dp\"\n\t\t\tandroid:layout_marginLeft=\"20dp\"\n\t\t\tandroid:layout_marginStart=\"20dp\"\n\t\t\tandroid:layout_marginRight=\"20dp\"\n\t\t\tandroid:layout_marginEnd=\"20dp\"\n\t\t\tandroid:textAllCaps=\"false\"\n\t\t\tandroid:text=\"@string/start_record\"\n\t\t\tandroid:id=\"@+id/btn_record\"\n\t\t/>\n\t\t\n\t\t<TextView\n\t\t\tandroid:layout_width=\"match_parent\"\n\t\t\tandroid:layout_height=\"wrap_content\"\n\t\t\tandroid:layout_margin=\"20dp\"\n\t\t\tandroid:text=\"@string/record_duration\"\n\t\t\tandroid:textColor=\"@android:color/black\"\n\t\t\tandroid:id=\"@+id/record_duration\"\n\t\t/>\n\t\t\n\t\t<TextView\n\t\t\tandroid:layout_width=\"match_parent\"\n\t\t\tandroid:layout_height=\"wrap_content\"\n\t\t\tandroid:layout_margin=\"20dp\"\n\t\t\tandroid:text=\"@string/record_size\"\n\t\t\tandroid:textColor=\"@android:color/black\"\n\t\t\tandroid:id=\"@+id/record_size\"\n\t\t/>\n\t\n\t</LinearLayout>\n\n</LinearLayout>\n"
  },
  {
    "path": "demo/src/main/res/layout/activity_processors_demonstrate.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n              android:orientation=\"vertical\"\n              android:layout_width=\"match_parent\"\n              android:layout_height=\"match_parent\">\n\t\n\t<LinearLayout\n\t\tandroid:layout_width=\"match_parent\"\n\t\tandroid:layout_height=\"0dp\"\n\t\tandroid:layout_weight=\"1\"\n\t\tandroid:layout_marginLeft=\"16dp\"\n\t\tandroid:layout_marginStart=\"16dp\"\n\t\tandroid:layout_marginEnd=\"16dp\"\n\t\tandroid:layout_marginRight=\"16dp\"\n\t\tandroid:paddingTop=\"10dp\"\n\t\tandroid:orientation=\"vertical\"\n\t>\n\t\t\n\t\t<TextView\n\t\t\tandroid:layout_width=\"match_parent\"\n\t\t\tandroid:layout_height=\"wrap_content\"\n\t\t\tandroid:id=\"@+id/tv_processor_1_title\"\n\t\t\tandroid:text=\"@string/processor_1_title\"\n\t\t\tandroid:textColor=\"@color/colorAccent\"/>\n\t\t\n\t\t<android.support.v7.widget.RecyclerView\n\t\t\tandroid:layout_width=\"match_parent\"\n\t\t\tandroid:layout_height=\"match_parent\"\n\t\t\tandroid:layout_marginTop=\"10dp\"\n\t\t\tandroid:id=\"@+id/rcv_processor_1\"/>\n\t\n\t</LinearLayout>\n\t\n\t<LinearLayout\n\t\tandroid:layout_width=\"match_parent\"\n\t\tandroid:layout_height=\"0dp\"\n\t\tandroid:layout_weight=\"1\"\n\t\tandroid:layout_marginLeft=\"16dp\"\n\t\tandroid:layout_marginStart=\"16dp\"\n\t\tandroid:layout_marginEnd=\"16dp\"\n\t\tandroid:layout_marginRight=\"16dp\"\n\t\tandroid:paddingTop=\"10dp\"\n\t\tandroid:orientation=\"vertical\"\n\t>\n\t\t<TextView\n\t\t\tandroid:layout_width=\"match_parent\"\n\t\t\tandroid:layout_height=\"wrap_content\"\n\t\t\tandroid:id=\"@+id/tv_processor_2_title\"\n\t\t\tandroid:text=\"@string/processor_1_title\"\n\t\t\tandroid:textColor=\"@color/colorAccent\"/>\n\t\t\n\t\t<android.support.v7.widget.RecyclerView\n\t\t\tandroid:layout_width=\"match_parent\"\n\t\t\tandroid:layout_height=\"match_parent\"\n\t\t\tandroid:layout_marginTop=\"10dp\"\n\t\t\tandroid:id=\"@+id/rcv_processor_2\"/>\n\t\n\t</LinearLayout>\n\t\n\t<Button\n\t\tandroid:layout_width=\"match_parent\"\n\t\tandroid:layout_height=\"wrap_content\"\n\t\tandroid:id=\"@+id/btn_record\"\n\t\tandroid:textAllCaps=\"false\"\n\t\tandroid:text=\"@string/start_record\"/>\n\n</LinearLayout>"
  },
  {
    "path": "demo/src/main/res/layout/activity_record_demonstrate.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n              android:orientation=\"vertical\"\n              android:layout_width=\"match_parent\"\n              android:layout_height=\"match_parent\">\n\t\n\t<LinearLayout\n\t\tandroid:layout_width=\"match_parent\"\n\t\tandroid:layout_height=\"wrap_content\"\n\t\tandroid:layout_margin=\"20dp\"\n\t\tandroid:orientation=\"vertical\"\n\t>\n\t\t\n\t\t<TextView\n\t\t\tandroid:layout_width=\"wrap_content\"\n\t\t\tandroid:layout_height=\"wrap_content\"\n\t\t\tandroid:text=\"@string/record_output_address\"\n\t\t/>\n\t\t\n\t\t<EditText\n\t\t\tandroid:layout_width=\"match_parent\"\n\t\t\tandroid:layout_height=\"wrap_content\"\n\t\t\tandroid:id=\"@+id/et_output_file\"\n\t\t\tandroid:inputType=\"text\"\n\t\t\tandroid:textColor=\"@android:color/black\"\n\t\t\tandroid:text=\"@string/sdcard_test_wav\"\n\t\t\tandroid:layout_marginTop=\"10dp\"/>\n\t\n\t</LinearLayout>\n\t\n\t\n\t<Button\n\t\tandroid:layout_width=\"match_parent\"\n\t\tandroid:layout_height=\"wrap_content\"\n\t\tandroid:layout_marginLeft=\"20dp\"\n\t\tandroid:layout_marginStart=\"20dp\"\n\t\tandroid:layout_marginRight=\"20dp\"\n\t\tandroid:layout_marginEnd=\"20dp\"\n\t\tandroid:textAllCaps=\"false\"\n\t\tandroid:text=\"@string/start_record\"\n\t\tandroid:id=\"@+id/btn_record\"\n\t/>\n\t\n\t<TextView\n\t\tandroid:layout_width=\"match_parent\"\n\t\tandroid:layout_height=\"wrap_content\"\n\t\tandroid:layout_margin=\"20dp\"\n\t\tandroid:text=\"@string/record_duration\"\n\t\tandroid:textColor=\"@android:color/black\"\n\t\tandroid:id=\"@+id/record_duration\"\n\t/>\n\t\n\t<TextView\n\t\tandroid:layout_width=\"match_parent\"\n\t\tandroid:layout_height=\"wrap_content\"\n\t\tandroid:layout_margin=\"20dp\"\n\t\tandroid:text=\"@string/record_size\"\n\t\tandroid:textColor=\"@android:color/black\"\n\t\tandroid:id=\"@+id/record_size\"\n\t/>\n\t\n\t<Button\n\t\tandroid:layout_width=\"match_parent\"\n\t\tandroid:layout_height=\"wrap_content\"\n\t\tandroid:layout_marginLeft=\"20dp\"\n\t\tandroid:layout_marginStart=\"20dp\"\n\t\tandroid:layout_marginRight=\"20dp\"\n\t\tandroid:layout_marginEnd=\"20dp\"\n\t\tandroid:textAllCaps=\"false\"\n\t\tandroid:text=\"@string/play_record\"\n\t\tandroid:id=\"@+id/btn_play\"\n\t\tandroid:enabled=\"false\"\n\t/>\n\n\n</LinearLayout>"
  },
  {
    "path": "demo/src/main/res/layout/activity_volume.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:orientation=\"vertical\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\">\n\n    <Button\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_marginLeft=\"20dp\"\n        android:layout_marginStart=\"20dp\"\n        android:layout_marginRight=\"20dp\"\n        android:layout_marginEnd=\"20dp\"\n        android:layout_marginTop=\"20dp\"\n        android:textAllCaps=\"false\"\n        android:text=\"@string/start_record\"\n        android:id=\"@+id/btn_record\" />\n\n    <com.liulishuo.engzo.lingorecorder.demo.view.VolumeView\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"100dp\"\n        android:id=\"@+id/volume_view\" />\n\n</LinearLayout>"
  },
  {
    "path": "demo/src/main/res/values/colors.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n    <color name=\"colorPrimary\">#3F51B5</color>\n    <color name=\"colorPrimaryDark\">#303F9F</color>\n    <color name=\"colorAccent\">#FF4081</color>\n</resources>\n"
  },
  {
    "path": "demo/src/main/res/values/strings.xml",
    "content": "<resources>\n\t<string name=\"app_name\">LingoRecorder</string>\n\t<string name=\"check_permission_title\">Permission check</string>\n\t<string name=\"check_permission_content\">Need to provide recording and storage permissions.\n\t</string>\n\t<string name=\"check_permission_fail\">Permission fetch failed</string>\n\t<string name=\"confirm\">OK</string>\n\t<string name=\"record_demonstrate\">录音演示</string>\n\t<string name=\"start_record\">Start Record</string>\n\t<string name=\"record_duration\">录音时长：%s</string>\n\t<string name=\"record_output_address\">录音文件输出地址:</string>\n\t<string name=\"sdcard_test_wav\">/sdcard/test.wav</string>\n\t<string name=\"play_record\">Play Record</string>\n\t<string name=\"stop_record\">Stop Record</string>\n\t<string name=\"record_failed\">录音出错</string>\n\t<string name=\"process_failed\">处理录音出错</string>\n\t<string name=\"record_size\">文件大小：%s</string>\n\t<string name=\"start_scorer\">开始打分</string>\n\t<string name=\"custom_processors_demonstrate\">自定义处理器演示</string>\n\t<string name=\"flac_demonstrate\">硬编码 Flac 演示</string>\n\t<string name=\"across_process_processor_demonstrate\">跨进程处理器演示</string>\n\t<string name=\"processor_1_title\">Processor 1 : %s</string>\n\t<string name=\"processor_2_title\">Processor 2 : %s</string>\n\t<string name=\"flac_unsupport\">抱歉, 该机型不支持 Flac 编码器</string>\n\t<string name=\"sdcard_test_flac\">/sdcard/test.flac</string>\n\t<string name=\"please_read\">请读：</string>\n\t<string name=\"scorer_sentence\">I will study english very hard.</string>\n\t<string name=\"scorer_result\">打分结果：%s</string>\n\t<string name=\"stop_scorer\">结束打分</string>\n\t<string name=\"volume_demonstrate\">音量演示</string>\n</resources>\n"
  },
  {
    "path": "demo/src/main/res/values/styles.xml",
    "content": "<resources>\n\n    <!-- Base application theme. -->\n    <style name=\"AppTheme\" parent=\"Theme.AppCompat.Light.DarkActionBar\">\n        <!-- Customize your theme here. -->\n        <item name=\"colorPrimary\">@color/colorPrimary</item>\n        <item name=\"colorPrimaryDark\">@color/colorPrimaryDark</item>\n        <item name=\"colorAccent\">@color/colorAccent</item>\n    </style>\n\n</resources>\n"
  },
  {
    "path": "demo/src/test/java/com/liulishuo/engzo/lingorecorder/ExampleUnitTest.java",
    "content": "package com.liulishuo.engzo.lingorecorder;\n\nimport org.junit.Test;\n\nimport static org.junit.Assert.*;\n\n/**\n * Example local unit test, which will execute on the development machine (host).\n *\n * @see <a href=\"http://d.android.com/tools/testing\">Testing documentation</a>\n */\npublic class ExampleUnitTest {\n    @Test\n    public void addition_isCorrect() throws Exception {\n        assertEquals(4, 2 + 2);\n    }\n}"
  },
  {
    "path": "gradle/bintray.gradle",
    "content": "/*\n * Copyright (c) 2018 LingoChamp Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\napply plugin: 'com.jfrog.bintray'\n\nafterEvaluate { project ->\n    task sourcesJar(type: Jar) {\n        from android.sourceSets.main.java.srcDirs\n        classifier = 'sources'\n    }\n\n    task javadoc(type: Javadoc) {\n        failOnError false\n        source = android.sourceSets.main.java.srcDirs\n        options {\n            charSet = 'UTF-8'\n            links \"http://docs.oracle.com/javase/7/docs/api/\"\n            linksOffline \"http://d.android.com/reference\", System.getenv(\"ANDROID_HOME\") + \"/docs/reference\"\n        }\n        classpath += project.android.libraryVariants.toList().first().javaCompile.classpath\n        classpath += project.files(android.getBootClasspath().join(File.pathSeparator))\n    }\n\n    task javadocJar(type: Jar, dependsOn: javadoc) {\n        classifier = 'javadoc'\n        from javadoc.destinationDir\n    }\n\n    artifacts {\n        archives javadocJar\n        archives sourcesJar\n    }\n}\n\n\ndef getBintrayUser() {\n    return hasProperty('BINTRAY_USER') ? BINTRAY_USER : \"\"\n}\n\ndef getBintrayGPGPassword() {\n    return hasProperty('BINTRAY_GPG_PASSWORD') ? BINTRAY_GPG_PASSWORD : \"\"\n}\n\ndef getBintrayApiKey() {\n    return hasProperty('BINTRAY_API_KEY') ? BINTRAY_API_KEY : \"\"\n}\n\ndef getSonatypeUsername() {\n    return hasProperty('SONATYPE_NEXUS_USERNAME') ? SONATYPE_NEXUS_USERNAME : \"\"\n}\n\ndef getSonatypePassword() {\n    return hasProperty('SONATYPE_NEXUS_PASSWORD') ? SONATYPE_NEXUS_PASSWORD : \"\"\n}\nversion = VERSION_NAME\n\nbintray {\n    user = getBintrayUser()\n    key = getBintrayApiKey()\n\n//    publish = true //[Default: false] Whether version should be auto published after an upload\n//    override = false //[Default: false] Whether to override version artifacts already published\n\n    configurations = ['archives']\n    pkg {\n        repo = \"maven\"\n        name = POM_NAME\n        desc = POM_DESCRIPTION\n        websiteUrl = POM_URL\n        issueTrackerUrl = ISSUE_URL\n        vcsUrl = POM_SCM_URL\n        licenses = [\"Apache-2.0\"]\n        publish = true\n        publicDownloadNumbers = true\n\n        githubRepo = POM_URL\n        githubReleaseNotesFile = 'README.md'\n\n        version {\n            gpg {\n                sign = true //Determines whether to GPG sign the files. The default is false\n                passphrase = getBintrayGPGPassword()\n            }\n\n            mavenCentralSync {\n                sync = true\n                user = getSonatypeUsername()\n                password = getSonatypePassword()\n                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.\n            }\n        }\n    }\n}"
  },
  {
    "path": "gradle/mvn-local.gradle",
    "content": "/*\n * Copyright (c) 2018 LingoChamp Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\napply plugin: 'maven-publish'\n\ntask sourceJar(type: Jar) {\n    from android.sourceSets.main.java.srcDirs\n    classifier \"source\"\n}\n\npublishing {\n    publications {\n        lingoRecorder(MavenPublication) {\n            groupId GROUP\n            artifactId POM_ARTIFACT_ID\n            version VERSION_NAME\n            artifact(sourceJar)\n            artifact(\"$buildDir/outputs/aar/${project.name}-release.aar\")\n\n            pom.withXml {\n                def dependenciesNode = asNode().appendNode('dependencies')\n                configurations.compile.allDependencies.each {\n                    if (it.group != null\n                            && (it.name != null || \"unspecified\" == it.name)\n                            && it.version != null) {\n                        def dependencyNode = dependenciesNode.appendNode('dependency')\n                        dependencyNode.appendNode('groupId', it.group)\n                        dependencyNode.appendNode('artifactId', it.name)\n                        dependencyNode.appendNode('version', it.version)\n                    }\n                }\n            }\n        }\n    }\n}"
  },
  {
    "path": "gradle/mvn-push.gradle",
    "content": "/*\n * Copyright 2013 Chris Banes\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\napply plugin: 'maven'\napply plugin: 'signing'\napply from: '../gradle/mvn-local.gradle'\napply from: '../gradle/bintray.gradle'\n\nversion = VERSION_NAME\ngroup = GROUP\n\ndef isReleaseBuild() {\n  return VERSION_NAME.contains(\"SNAPSHOT\") == false\n}\n\ndef getReleaseRepositoryUrl() {\n  return hasProperty('RELEASE_REPOSITORY_URL') ? RELEASE_REPOSITORY_URL :\n      \"https://oss.sonatype.org/service/local/staging/deploy/maven2/\"\n}\n\ndef getSnapshotRepositoryUrl() {\n  return hasProperty('SNAPSHOT_REPOSITORY_URL') ? SNAPSHOT_REPOSITORY_URL :\n      \"https://oss.sonatype.org/content/repositories/snapshots/\"\n}\n\ndef getRepositoryUsername() {\n  return hasProperty('SONATYPE_NEXUS_USERNAME') ? SONATYPE_NEXUS_USERNAME : \"\"\n}\n\ndef getRepositoryPassword() {\n  return hasProperty('SONATYPE_NEXUS_PASSWORD') ? SONATYPE_NEXUS_PASSWORD : \"\"\n}\n\nafterEvaluate { project ->\n  uploadArchives {\n    repositories {\n      mavenDeployer {\n        beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }\n\n        pom.groupId = GROUP\n        pom.artifactId = POM_ARTIFACT_ID\n        pom.version = VERSION_NAME\n\n        repository(url: getReleaseRepositoryUrl()) {\n          authentication(userName: getRepositoryUsername(), password: getRepositoryPassword())\n        }\n        snapshotRepository(url: getSnapshotRepositoryUrl()) {\n          authentication(userName: getRepositoryUsername(), password: getRepositoryPassword())\n        }\n\n        pom.project {\n          name POM_NAME\n          packaging POM_PACKAGING\n          description POM_DESCRIPTION\n          url POM_URL\n\n          scm {\n            url POM_SCM_URL\n            connection POM_SCM_CONNECTION\n            developerConnection POM_SCM_DEV_CONNECTION\n          }\n\n          licenses {\n            license {\n              name POM_LICENCE_NAME\n              url POM_LICENCE_URL\n              distribution POM_LICENCE_DIST\n            }\n          }\n\n          developers {\n            developer {\n              id POM_DEVELOPER_ID\n              name POM_DEVELOPER_NAME\n            }\n          }\n        }\n      }\n    }\n  }\n\n  signing {\n    required { isReleaseBuild() && gradle.taskGraph.hasTask(\"uploadArchives\") }\n    sign configurations.archives\n  }\n\n  if (project.getPlugins().hasPlugin('com.android.application') ||\n      project.getPlugins().hasPlugin('com.android.library')) {\n    task install(type: Upload, dependsOn: assemble) {\n      repositories.mavenInstaller {\n        configuration = configurations.archives\n\n        pom.groupId = GROUP\n        pom.artifactId = POM_ARTIFACT_ID\n        pom.version = VERSION_NAME\n\n        pom.project {\n          name POM_NAME\n          packaging POM_PACKAGING\n          description POM_DESCRIPTION\n          url POM_URL\n\n          scm {\n            url POM_SCM_URL\n            connection POM_SCM_CONNECTION\n            developerConnection POM_SCM_DEV_CONNECTION\n          }\n\n          licenses {\n            license {\n              name POM_LICENCE_NAME\n              url POM_LICENCE_URL\n              distribution POM_LICENCE_DIST\n            }\n          }\n\n          developers {\n            developer {\n              id POM_DEVELOPER_ID\n              name POM_DEVELOPER_NAME\n            }\n          }\n        }\n      }\n    }\n\n    task androidJavadocs(type: Javadoc) {\n      source = android.sourceSets.main.java.source\n      classpath += project.files(android.getBootClasspath().join(File.pathSeparator))\n    }\n\n    task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) {\n      classifier = 'javadoc'\n      from androidJavadocs.destinationDir\n    }\n\n    task androidSourcesJar(type: Jar) {\n      classifier = 'sources'\n      from android.sourceSets.main.java.source\n    }\n  } else {\n    install {\n      repositories.mavenInstaller {\n        pom.groupId = GROUP\n        pom.artifactId = POM_ARTIFACT_ID\n        pom.version = VERSION_NAME\n\n        pom.project {\n          name POM_NAME\n          packaging POM_PACKAGING\n          description POM_DESCRIPTION\n          url POM_URL\n\n          scm {\n            url POM_SCM_URL\n            connection POM_SCM_CONNECTION\n            developerConnection POM_SCM_DEV_CONNECTION\n          }\n\n          licenses {\n            license {\n              name POM_LICENCE_NAME\n              url POM_LICENCE_URL\n              distribution POM_LICENCE_DIST\n            }\n          }\n\n          developers {\n            developer {\n              id POM_DEVELOPER_ID\n              name POM_DEVELOPER_NAME\n            }\n          }\n        }\n      }\n    }\n\n    task sourcesJar(type: Jar, dependsOn: classes) {\n      classifier = 'sources'\n      from sourceSets.main.allSource\n    }\n\n    task javadocJar(type: Jar, dependsOn: javadoc) {\n      classifier = 'javadoc'\n      from javadoc.destinationDir\n    }\n  }\n\n  if (JavaVersion.current().isJava8Compatible()) {\n    allprojects {\n      tasks.withType(Javadoc) {\n        options.addStringOption('Xdoclint:none', '-quiet')\n      }\n    }\n  }\n\n  artifacts {\n    if (project.getPlugins().hasPlugin('com.android.application') ||\n        project.getPlugins().hasPlugin('com.android.library')) {\n      archives androidSourcesJar\n      archives androidJavadocsJar\n    } else {\n      archives sourcesJar\n      archives javadocJar\n    }\n  }\n}\n"
  },
  {
    "path": "gradle/wrapper/gradle-wrapper.properties",
    "content": "#Mon Jul 31 15:15:58 CST 2017\ndistributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-5.5.1-all.zip\n"
  },
  {
    "path": "gradle.properties",
    "content": "# Project-wide Gradle settings.\n\n# IDE (e.g. Android Studio) users:\n# Gradle settings configured through the IDE *will override*\n# any settings specified in this file.\n\n# For more details on how to configure your build environment visit\n# http://www.gradle.org/docs/current/userguide/build_environment.html\n\n# Specifies the JVM arguments used for the daemon process.\n# The setting is particularly useful for tweaking memory settings.\norg.gradle.jvmargs=-Xmx1536m\n\n# When configured, Gradle will run in incubating parallel mode.\n# This option should only be used with decoupled projects. More details, visit\n# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects\n# org.gradle.parallel=true\n\nVERSION_NAME=1.2.5\n\nGROUP=com.liulishuo.engzo\n\nPOM_URL=https://github.com/lingochamp/LingoRecorder\nISSUE_URL=https://github.com/lingochamp/LingoRecorder/issues\n\nPOM_SCM_URL=https://github.com/lingochamp/LingoRecorder\nPOM_SCM_CONNECTION=scm:git@github.com:lingochamp/LingoRecorder.git\nPOM_SCM_DEV_CONNECTION=scm:git@github.com:lingochamp/LingoRecorder.git\n\nPOM_LICENCE_NAME=The Apache Software License, Version 2.0\nPOM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt\nPOM_LICENCE_DIST=repo\n\nPOM_DEVELOPER_ID=lingochamp\nPOM_DEVELOPER_NAME=LingoChamp Inc.\nandroid.useAndroidX=true\nandroid.enableJetifier=true\nandroid.debug.obsoleteApi=true\n"
  },
  {
    "path": "gradlew",
    "content": "#!/usr/bin/env bash\n\n##############################################################################\n##\n##  Gradle start up script for UN*X\n##\n##############################################################################\n\n# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\nDEFAULT_JVM_OPTS=\"\"\n\nAPP_NAME=\"Gradle\"\nAPP_BASE_NAME=`basename \"$0\"`\n\n# Use the maximum available, or set MAX_FD != -1 to use that value.\nMAX_FD=\"maximum\"\n\nwarn ( ) {\n    echo \"$*\"\n}\n\ndie ( ) {\n    echo\n    echo \"$*\"\n    echo\n    exit 1\n}\n\n# OS specific support (must be 'true' or 'false').\ncygwin=false\nmsys=false\ndarwin=false\ncase \"`uname`\" in\n  CYGWIN* )\n    cygwin=true\n    ;;\n  Darwin* )\n    darwin=true\n    ;;\n  MINGW* )\n    msys=true\n    ;;\nesac\n\n# Attempt to set APP_HOME\n# Resolve links: $0 may be a link\nPRG=\"$0\"\n# Need this for relative symlinks.\nwhile [ -h \"$PRG\" ] ; do\n    ls=`ls -ld \"$PRG\"`\n    link=`expr \"$ls\" : '.*-> \\(.*\\)$'`\n    if expr \"$link\" : '/.*' > /dev/null; then\n        PRG=\"$link\"\n    else\n        PRG=`dirname \"$PRG\"`\"/$link\"\n    fi\ndone\nSAVED=\"`pwd`\"\ncd \"`dirname \\\"$PRG\\\"`/\" >/dev/null\nAPP_HOME=\"`pwd -P`\"\ncd \"$SAVED\" >/dev/null\n\nCLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar\n\n# Determine the Java command to use to start the JVM.\nif [ -n \"$JAVA_HOME\" ] ; then\n    if [ -x \"$JAVA_HOME/jre/sh/java\" ] ; then\n        # IBM's JDK on AIX uses strange locations for the executables\n        JAVACMD=\"$JAVA_HOME/jre/sh/java\"\n    else\n        JAVACMD=\"$JAVA_HOME/bin/java\"\n    fi\n    if [ ! -x \"$JAVACMD\" ] ; then\n        die \"ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME\n\nPlease set the JAVA_HOME variable in your environment to match the\nlocation of your Java installation.\"\n    fi\nelse\n    JAVACMD=\"java\"\n    which java >/dev/null 2>&1 || die \"ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.\n\nPlease set the JAVA_HOME variable in your environment to match the\nlocation of your Java installation.\"\nfi\n\n# Increase the maximum file descriptors if we can.\nif [ \"$cygwin\" = \"false\" -a \"$darwin\" = \"false\" ] ; then\n    MAX_FD_LIMIT=`ulimit -H -n`\n    if [ $? -eq 0 ] ; then\n        if [ \"$MAX_FD\" = \"maximum\" -o \"$MAX_FD\" = \"max\" ] ; then\n            MAX_FD=\"$MAX_FD_LIMIT\"\n        fi\n        ulimit -n $MAX_FD\n        if [ $? -ne 0 ] ; then\n            warn \"Could not set maximum file descriptor limit: $MAX_FD\"\n        fi\n    else\n        warn \"Could not query maximum file descriptor limit: $MAX_FD_LIMIT\"\n    fi\nfi\n\n# For Darwin, add options to specify how the application appears in the dock\nif $darwin; then\n    GRADLE_OPTS=\"$GRADLE_OPTS \\\"-Xdock:name=$APP_NAME\\\" \\\"-Xdock:icon=$APP_HOME/media/gradle.icns\\\"\"\nfi\n\n# For Cygwin, switch paths to Windows format before running java\nif $cygwin ; then\n    APP_HOME=`cygpath --path --mixed \"$APP_HOME\"`\n    CLASSPATH=`cygpath --path --mixed \"$CLASSPATH\"`\n    JAVACMD=`cygpath --unix \"$JAVACMD\"`\n\n    # We build the pattern for arguments to be converted via cygpath\n    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`\n    SEP=\"\"\n    for dir in $ROOTDIRSRAW ; do\n        ROOTDIRS=\"$ROOTDIRS$SEP$dir\"\n        SEP=\"|\"\n    done\n    OURCYGPATTERN=\"(^($ROOTDIRS))\"\n    # Add a user-defined pattern to the cygpath arguments\n    if [ \"$GRADLE_CYGPATTERN\" != \"\" ] ; then\n        OURCYGPATTERN=\"$OURCYGPATTERN|($GRADLE_CYGPATTERN)\"\n    fi\n    # Now convert the arguments - kludge to limit ourselves to /bin/sh\n    i=0\n    for arg in \"$@\" ; do\n        CHECK=`echo \"$arg\"|egrep -c \"$OURCYGPATTERN\" -`\n        CHECK2=`echo \"$arg\"|egrep -c \"^-\"`                                 ### Determine if an option\n\n        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition\n            eval `echo args$i`=`cygpath --path --ignore --mixed \"$arg\"`\n        else\n            eval `echo args$i`=\"\\\"$arg\\\"\"\n        fi\n        i=$((i+1))\n    done\n    case $i in\n        (0) set -- ;;\n        (1) set -- \"$args0\" ;;\n        (2) set -- \"$args0\" \"$args1\" ;;\n        (3) set -- \"$args0\" \"$args1\" \"$args2\" ;;\n        (4) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" ;;\n        (5) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" ;;\n        (6) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" ;;\n        (7) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" \"$args6\" ;;\n        (8) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" \"$args6\" \"$args7\" ;;\n        (9) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" \"$args6\" \"$args7\" \"$args8\" ;;\n    esac\nfi\n\n# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules\nfunction splitJvmOpts() {\n    JVM_OPTS=(\"$@\")\n}\neval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS\nJVM_OPTS[${#JVM_OPTS[*]}]=\"-Dorg.gradle.appname=$APP_BASE_NAME\"\n\nexec \"$JAVACMD\" \"${JVM_OPTS[@]}\" -classpath \"$CLASSPATH\" org.gradle.wrapper.GradleWrapperMain \"$@\"\n"
  },
  {
    "path": "gradlew.bat",
    "content": "@if \"%DEBUG%\" == \"\" @echo off\n@rem ##########################################################################\n@rem\n@rem  Gradle startup script for Windows\n@rem\n@rem ##########################################################################\n\n@rem Set local scope for the variables with windows NT shell\nif \"%OS%\"==\"Windows_NT\" setlocal\n\n@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\nset DEFAULT_JVM_OPTS=\n\nset DIRNAME=%~dp0\nif \"%DIRNAME%\" == \"\" set DIRNAME=.\nset APP_BASE_NAME=%~n0\nset APP_HOME=%DIRNAME%\n\n@rem Find java.exe\nif defined JAVA_HOME goto findJavaFromJavaHome\n\nset JAVA_EXE=java.exe\n%JAVA_EXE% -version >NUL 2>&1\nif \"%ERRORLEVEL%\" == \"0\" goto init\n\necho.\necho ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.\necho.\necho Please set the JAVA_HOME variable in your environment to match the\necho location of your Java installation.\n\ngoto fail\n\n:findJavaFromJavaHome\nset JAVA_HOME=%JAVA_HOME:\"=%\nset JAVA_EXE=%JAVA_HOME%/bin/java.exe\n\nif exist \"%JAVA_EXE%\" goto init\n\necho.\necho ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%\necho.\necho Please set the JAVA_HOME variable in your environment to match the\necho location of your Java installation.\n\ngoto fail\n\n:init\n@rem Get command-line arguments, handling Windowz variants\n\nif not \"%OS%\" == \"Windows_NT\" goto win9xME_args\nif \"%@eval[2+2]\" == \"4\" goto 4NT_args\n\n:win9xME_args\n@rem Slurp the command line arguments.\nset CMD_LINE_ARGS=\nset _SKIP=2\n\n:win9xME_args_slurp\nif \"x%~1\" == \"x\" goto execute\n\nset CMD_LINE_ARGS=%*\ngoto execute\n\n:4NT_args\n@rem Get arguments from the 4NT Shell from JP Software\nset CMD_LINE_ARGS=%$\n\n:execute\n@rem Setup the command line\n\nset CLASSPATH=%APP_HOME%\\gradle\\wrapper\\gradle-wrapper.jar\n\n@rem Execute Gradle\n\"%JAVA_EXE%\" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% \"-Dorg.gradle.appname=%APP_BASE_NAME%\" -classpath \"%CLASSPATH%\" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%\n\n:end\n@rem End local scope for the variables with windows NT shell\nif \"%ERRORLEVEL%\"==\"0\" goto mainEnd\n\n:fail\nrem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of\nrem the _cmd.exe /c_ return code!\nif  not \"\" == \"%GRADLE_EXIT_CONSOLE%\" exit 1\nexit /b 1\n\n:mainEnd\nif \"%OS%\"==\"Windows_NT\" endlocal\n\n:omega\n"
  },
  {
    "path": "library/build.gradle",
    "content": "apply plugin: 'com.android.library'\n\nandroid {\n    compileSdkVersion 28\n\n    defaultConfig {\n        minSdkVersion 15\n        targetSdkVersion 28\n        versionCode 1\n        versionName \"1.0\"\n\n        testInstrumentationRunner \"androidx.test.runner.AndroidJUnitRunner\"\n\n    }\n    buildTypes {\n        release {\n            minifyEnabled false\n            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\n        }\n    }\n}\n\ndependencies {\n    implementation fileTree(dir: 'libs', include: ['*.jar'])\n    androidTestImplementation('androidx.test.espresso:espresso-core:3.1.0', {\n        exclude group: 'com.android.support', module: 'support-annotations'\n    })\n    androidTestImplementation 'androidx.test:runner:1.2.0'\n    androidTestImplementation 'androidx.test:rules:1.2.0'\n    androidTestImplementation 'org.hamcrest:hamcrest-library:1.3'\n    testImplementation 'junit:junit:4.12'\n    implementation 'androidx.annotation:annotation:1.1.0'\n}\n\napply from: rootProject.file('gradle/mvn-push.gradle')\n"
  },
  {
    "path": "library/gradle.properties",
    "content": "POM_ARTIFACT_ID=lingo-recorder\nPOM_NAME=LingoRecorder\nPOM_DESCRIPTION=LingoRecord is a better recorder for Android, you can easily process pcm data from it\nPOM_PACKAGING=aar\n"
  },
  {
    "path": "library/proguard-rules.pro",
    "content": "# Add project specific ProGuard rules here.\n# By default, the flags in this file are appended to flags specified\n# in /Users/wcw/dev/sdk/tools/proguard/proguard-android.txt\n# You can edit the include path and order by changing the proguardFiles\n# directive in build.gradle.\n#\n# For more details, see\n#   http://developer.android.com/guide/developing/tools/proguard.html\n\n# Add any project specific keep options here:\n\n# If your project uses WebView with JS, uncomment the following\n# and specify the fully qualified class name to the JavaScript interface\n# class:\n#-keepclassmembers class fqcn.of.javascript.interface.for.webview {\n#   public *;\n#}\n"
  },
  {
    "path": "library/src/androidTest/AndroidManifest.xml",
    "content": "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    package=\"com.liulishuo.engzo.lingorecorder\">\n\n    <uses-permission android:name=\"android.permission.RECORD_AUDIO\" />\n    <uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\" />\n\n    <application android:allowBackup=\"true\"\n        android:supportsRtl=\"true\">\n\n    </application>\n\n</manifest>\n"
  },
  {
    "path": "library/src/androidTest/java/com/liulishuo/engzo/lingorecorder/CancelRecordTest.java",
    "content": "package com.liulishuo.engzo.lingorecorder;\n\nimport android.Manifest;\nimport android.util.Log;\n\nimport androidx.test.filters.SmallTest;\nimport androidx.test.rule.GrantPermissionRule;\nimport androidx.test.runner.AndroidJUnit4;\n\nimport com.liulishuo.engzo.lingorecorder.processor.AudioProcessor;\n\nimport junit.framework.Assert;\n\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\n\nimport java.util.Map;\nimport java.util.concurrent.CountDownLatch;\n\n/**\n * Created by wcw on 8/9/17.\n */\n\n@RunWith(AndroidJUnit4.class)\n@SmallTest\npublic class CancelRecordTest {\n\n    @Rule\n    public GrantPermissionRule pr = GrantPermissionRule.grant(\n            Manifest.permission.RECORD_AUDIO,\n            Manifest.permission.WRITE_EXTERNAL_STORAGE);\n\n    private LingoRecorder lingoRecorder;\n\n    @Before\n    public void before() {\n        lingoRecorder = new LingoRecorder();\n    }\n\n    @Test\n    public void testCancelRecorderWhenProcessingBlock() {\n        lingoRecorder.put(\"blockProcessing\", new AudioProcessor() {\n\n            private void block(long time) throws InterruptedException {\n                Thread.sleep(time);\n            }\n\n            @Override\n            public void start() throws Exception {\n                block(100000);\n            }\n\n            @Override\n            public void flow(byte[] bytes, int size) throws Exception {\n                block(100000);\n            }\n\n            @Override\n            public boolean needExit() {\n                return false;\n            }\n\n            @Override\n            public void end() throws Exception {\n                block(100000);\n            }\n\n            @Override\n            public void release() {\n\n            }\n        });\n\n        final CountDownLatch countDownLatch = new CountDownLatch(2);\n\n        final Throwable[] throwableArray = new Throwable[2];\n\n        lingoRecorder.setOnProcessStopListener(new LingoRecorder.OnProcessStopListener() {\n            @Override\n            public void onProcessStop(Throwable throwable, Map<String, AudioProcessor> map) {\n                throwableArray[1] = throwable;\n                countDownLatch.countDown();\n            }\n        });\n\n        lingoRecorder.setOnRecordStopListener(new LingoRecorder.OnRecordStopListener() {\n            @Override\n            public void onRecordStop(Throwable throwable, Result result) {\n                throwableArray[0] = throwable;\n                countDownLatch.countDown();\n            }\n        });\n\n        lingoRecorder.start();\n        try {\n            Thread.sleep(5000);\n        } catch (InterruptedException ignore) {\n        }\n\n        lingoRecorder.cancel();\n\n        long startCancelTime = System.currentTimeMillis();\n\n        try {\n            countDownLatch.await();\n        } catch (InterruptedException ignore) {\n        }\n\n        long cancelCostTime = System.currentTimeMillis() - startCancelTime;\n\n        Assert.assertTrue(cancelCostTime < 1000);\n\n        Assert.assertNull(throwableArray[0]);\n        Assert.assertNotNull(throwableArray[1]);\n        Log.e(CancelRecordTest.class.getSimpleName(), Log.getStackTraceString(throwableArray[1]));\n        Assert.assertEquals(LingoRecorder.CancelProcessingException.class, throwableArray[1].getClass());\n    }\n\n}\n"
  },
  {
    "path": "library/src/androidTest/java/com/liulishuo/engzo/lingorecorder/LingoRecorderTest.java",
    "content": "package com.liulishuo.engzo.lingorecorder;\n\nimport androidx.test.filters.SmallTest;\nimport androidx.test.runner.AndroidJUnit4;\n\nimport com.liulishuo.engzo.lingorecorder.processor.AudioProcessor;\nimport com.liulishuo.engzo.lingorecorder.processor.TimerProcessor;\n\nimport junit.framework.Assert;\n\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\n\nimport java.io.File;\nimport java.util.Map;\nimport java.util.concurrent.CountDownLatch;\nimport java.util.concurrent.TimeUnit;\n\n/**\n * Created by wcw on 8/9/17.\n */\n\n@RunWith(AndroidJUnit4.class)\n@SmallTest\npublic class LingoRecorderTest {\n\n    private LingoRecorder lingoRecorder;\n\n    @Before\n    public void before() {\n        lingoRecorder = new LingoRecorder();\n    }\n\n    @Test\n    public void testRecorderStopWhenProcessorThrowException() {\n        lingoRecorder.put(\"exception\", new AudioProcessor() {\n            @Override\n            public void start() throws Exception {\n\n            }\n\n            @Override\n            public void flow(byte[] bytes, int size) throws Exception {\n                throw new RuntimeException(\"exception\");\n            }\n\n            @Override\n            public boolean needExit() {\n                return false;\n            }\n\n            @Override\n            public void end() throws Exception {\n\n            }\n\n            @Override\n            public void release() {\n\n            }\n        });\n        lingoRecorder.put(\"timer\", new TimerProcessor(lingoRecorder.getRecorderProperty(), 1000));\n\n        final CountDownLatch countDownLatch = new CountDownLatch(2);\n\n        final boolean[] status = new boolean[1];\n\n        lingoRecorder.setOnRecordStopListener(new LingoRecorder.OnRecordStopListener() {\n            @Override\n            public void onRecordStop(Throwable throwable, Result result) {\n                countDownLatch.countDown();\n                status[0] = true;\n            }\n        });\n\n        lingoRecorder.setOnProcessStopListener(new LingoRecorder.OnProcessStopListener() {\n            @Override\n            public void onProcessStop(Throwable throwable, Map<String, AudioProcessor> map) {\n                countDownLatch.countDown();\n            }\n        });\n\n        lingoRecorder.start();\n\n        try {\n            countDownLatch.await(2000, TimeUnit.MILLISECONDS);\n        } catch (InterruptedException e) {\n            e.printStackTrace();\n        }\n\n        Assert.assertTrue(status[0]);\n\n\n    }\n\n    private long getFileSize(String file) {\n        return new File(file).length();\n    }\n}\n"
  },
  {
    "path": "library/src/androidTest/java/com/liulishuo/engzo/lingorecorder/RecordAndProcessorEndTest.java",
    "content": "package com.liulishuo.engzo.lingorecorder;\n\nimport androidx.test.filters.SmallTest;\nimport androidx.test.runner.AndroidJUnit4;\n\nimport com.liulishuo.engzo.lingorecorder.processor.AudioProcessor;\n\nimport org.hamcrest.CoreMatchers;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\n\nimport java.util.Map;\nimport java.util.concurrent.CountDownLatch;\n\n/**\n * Created by rantianhua on 17/7/31.\n * this class will test the end callback of record and processor\n * will be invoked at a fixed order. (recorder end callback always first)\n */\n\n@RunWith(AndroidJUnit4.class)\n@SmallTest\npublic class RecordAndProcessorEndTest {\n\n    private AudioProcessor testProcessor;\n    private LingoRecorder lingoRecorder;\n    private long recorderEnd;\n    private long processorEnd;\n\n    @Before\n    public void before() {\n        lingoRecorder = new LingoRecorder();\n    }\n\n    @Test\n    public void recorderEndFirstRecorderCallbackFirst() throws Exception {\n        testProcessor = new AudioProcessor() {\n            @Override\n            public void start() throws Exception {\n\n            }\n\n            @Override\n            public void flow(byte[] bytes, int size) throws Exception {\n\n            }\n\n            @Override\n            public boolean needExit() {\n                return false;\n            }\n\n            @Override\n            public void end() throws Exception {\n\n            }\n\n            @Override\n            public void release() {\n\n            }\n        };\n        lingoRecorder.put(\"test1\", testProcessor);\n\n        final CountDownLatch countDownLatch = new CountDownLatch(2);\n\n        lingoRecorder.setOnRecordStopListener(new LingoRecorder.OnRecordStopListener() {\n\n            @Override\n            public void onRecordStop(Throwable throwable,\n                    Result result) {\n                recorderEnd = System.nanoTime();\n                countDownLatch.countDown();\n            }\n\n        });\n        lingoRecorder.setOnProcessStopListener(new LingoRecorder.OnProcessStopListener() {\n            @Override\n            public void onProcessStop(Throwable throwable, Map<String, AudioProcessor> map) {\n                processorEnd = System.nanoTime();\n                countDownLatch.countDown();\n            }\n        });\n\n        lingoRecorder.start();\n        sleep();\n        lingoRecorder.stop();\n\n        countDownLatch.await();\n\n        Assert.assertTrue(\"OnProcessStopListener must callback after OnRecordStopListener\",\n                processorEnd > recorderEnd);\n    }\n\n    private void sleep() {\n        try {\n            Thread.sleep(1000);\n        } catch (Exception ignore) {\n\n        }\n    }\n\n    private String processorErrorMsg = null;\n    @Test\n    public void processorMayEndFirstRecorderCallbackFirst() throws Exception {\n        final String errorMsg = \"hah\";\n        testProcessor = new AudioProcessor() {\n            @Override\n            public void start() throws Exception {\n                throw new RuntimeException(errorMsg);\n            }\n\n            @Override\n            public void flow(byte[] bytes, int size) throws Exception {\n\n            }\n\n            @Override\n            public boolean needExit() {\n                return false;\n            }\n\n            @Override\n            public void end() throws Exception {\n\n            }\n\n            @Override\n            public void release() {\n\n            }\n        };\n        lingoRecorder.put(\"test2\", testProcessor);\n\n        final CountDownLatch countDownLatch = new CountDownLatch(2);\n\n\n        lingoRecorder.setOnRecordStopListener(new LingoRecorder.OnRecordStopListener() {\n\n            @Override\n            public void onRecordStop(Throwable throwable,\n                    Result result) {\n                recorderEnd = System.nanoTime();\n                countDownLatch.countDown();\n            }\n        });\n        lingoRecorder.setOnProcessStopListener(new LingoRecorder.OnProcessStopListener() {\n            @Override\n            public void onProcessStop(Throwable throwable, Map<String, AudioProcessor> map) {\n                processorErrorMsg = throwable.getMessage();\n                processorEnd = System.nanoTime();\n                countDownLatch.countDown();\n            }\n        });\n\n        lingoRecorder.start();\n        sleep();\n        lingoRecorder.stop();\n\n        countDownLatch.await();\n\n        Assert.assertTrue(\"OnProcessStopListener must callback after OnRecordStopListener\",\n                processorEnd > recorderEnd);\n        Assert.assertThat(\"processor exception should be obtained by OnProcessStopListener\",\n                processorErrorMsg,\n                CoreMatchers.is(errorMsg));\n    }\n\n}\n"
  },
  {
    "path": "library/src/main/AndroidManifest.xml",
    "content": "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    package=\"com.liulishuo.engzo.lingorecorder\">\n\n    <application android:allowBackup=\"true\"\n        android:supportsRtl=\"true\">\n\n    </application>\n\n</manifest>\n"
  },
  {
    "path": "library/src/main/aidl/com/liulishuo/engzo/IAudioProcessorService.aidl",
    "content": "package com.liulishuo.engzo;\n\ninterface IAudioProcessorService {\n\n    void init(in Bundle bundle);\n\n    void start();\n    void flow(in byte[] bytes, int result);\n    boolean needExit();\n    void end();\n    void release();\n\n    Bundle getResult();\n\n}\n\n"
  },
  {
    "path": "library/src/main/java/com/liulishuo/engzo/lingorecorder/LingoRecorder.java",
    "content": "package com.liulishuo.engzo.lingorecorder;\n\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.os.Message;\n\nimport androidx.annotation.NonNull;\n\nimport com.liulishuo.engzo.lingorecorder.processor.AudioProcessor;\nimport com.liulishuo.engzo.lingorecorder.processor.WavProcessor;\nimport com.liulishuo.engzo.lingorecorder.recorder.AndroidRecorder;\nimport com.liulishuo.engzo.lingorecorder.recorder.IRecorder;\nimport com.liulishuo.engzo.lingorecorder.recorder.WavFileRecorder;\nimport com.liulishuo.engzo.lingorecorder.utils.LOG;\nimport com.liulishuo.engzo.lingorecorder.utils.RecorderProperty;\nimport com.liulishuo.engzo.lingorecorder.utils.WrapBuffer;\nimport com.liulishuo.engzo.lingorecorder.volume.DefaultVolumeCalculator;\nimport com.liulishuo.engzo.lingorecorder.volume.IVolumeCalculator;\nimport com.liulishuo.engzo.lingorecorder.volume.OnVolumeListener;\n\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.concurrent.LinkedBlockingQueue;\n\n\n/**\n * Created by wcw on 3/28/17.\n */\n\npublic class LingoRecorder {\n\n    private Map<String, AudioProcessor> audioProcessorMap = new HashMap<>();\n    private InternalRecorder internalRecorder;\n\n    private final static int MESSAGE_RECORD_STOP = 1;\n    private final static int MESSAGE_PROCESS_STOP = 2;\n    private final static int MESSAGE_VOLUME = 4;\n    private final static String KEY_DURATION = \"duration\";\n    private final static String KEY_FILEPATH = \"filePath\";\n\n    private OnRecordStopListener onRecordStopListener;\n    private OnProcessStopListener onProcessStopListener;\n    private OnVolumeListener onVolumeListener;\n    private IVolumeCalculator volumeCalculator;\n\n    private boolean available = true;\n    private boolean isProcessing = false;\n\n    private final RecorderProperty recorderProperty;\n\n    private String wavFilePath;\n\n    public LingoRecorder() {\n        this.recorderProperty = new RecorderProperty();\n    }\n\n    public boolean isProcessing() {\n        return isProcessing;\n    }\n\n    /**\n     *\n     * @deprecated use {@link #isProcessing()} instead\n     */\n    @Deprecated\n    public boolean isAvailable() {\n        return available;\n    }\n\n    public boolean isRecording() {\n        return internalRecorder != null;\n    }\n\n    public boolean start() {\n        return start(null);\n    }\n\n    public boolean start(String outputFilePath) {\n        if (internalRecorder != null || isProcessing) {\n            if (internalRecorder != null) {\n                LOG.e(\"start fail recorder is recording\");\n            } else {\n                LOG.e(\"start fail recorder is processing\");\n            }\n            return false;\n        }\n        LOG.d(\"start record\");\n        IRecorder recorder = null;\n        if (wavFilePath != null) {\n            recorder = new WavFileRecorder(wavFilePath, recorderProperty);\n            // wavFileRecorder not support stop\n            // LingoRecorder will be available until process finish\n            available = false;\n        } else {\n            recorder = new AndroidRecorder(recorderProperty);\n        }\n\n        // clone audioProcessorMap and skip null processor\n        Map<String, AudioProcessor> immutableMap = new HashMap<>(audioProcessorMap.size());\n        for (String key : audioProcessorMap.keySet()) {\n            AudioProcessor audioProcessor = audioProcessorMap.get(key);\n            if (audioProcessor != null) {\n                immutableMap.put(key, audioProcessor);\n            }\n        }\n        internalRecorder = new InternalRecorder(recorder, outputFilePath, immutableMap.values(),\n                new RecorderHandler(this, immutableMap),\n                volumeCalculator);\n        isProcessing = true;\n        internalRecorder.start();\n        return true;\n    }\n\n    public void stop() {\n        if (internalRecorder != null) {\n            LOG.d(\"end record\");\n            available = false;\n            LOG.d(\"record unavailable now\");\n            internalRecorder.stop();\n            internalRecorder = null;\n        }\n    }\n\n    public void cancel() {\n        if (internalRecorder != null) {\n            available = false;\n            internalRecorder.cancel();\n            internalRecorder = null;\n        }\n    }\n\n    public void setOnRecordStopListener(OnRecordStopListener onRecordStopListener) {\n        this.onRecordStopListener = onRecordStopListener;\n    }\n\n    public void setOnProcessStopListener(OnProcessStopListener onProcessStopListener) {\n        this.onProcessStopListener = onProcessStopListener;\n    }\n\n    public void setOnVolumeListener(OnVolumeListener onVolumeListener) {\n        setOnVolumeListener(onVolumeListener, new DefaultVolumeCalculator());\n    }\n\n    public void setOnVolumeListener(OnVolumeListener onVolumeListener, IVolumeCalculator volumeCalculator) {\n        this.onVolumeListener = onVolumeListener;\n        this.volumeCalculator = volumeCalculator;\n    }\n\n    public void put(String processorId, AudioProcessor processor) {\n        audioProcessorMap.put(processorId, processor);\n    }\n\n    public AudioProcessor remove(String processorId) {\n        return audioProcessorMap.remove(processorId);\n    }\n\n    public interface OnRecordStopListener {\n\n        class Result {\n            private long durationInMills;\n            private String outputFilePath;\n\n            public long getDurationInMills() {\n                return durationInMills;\n            }\n\n            public String getOutputFilePath() {\n                return outputFilePath;\n            }\n        }\n\n        void onRecordStop(Throwable throwable, Result result);\n    }\n\n    public interface OnProcessStopListener {\n        void onProcessStop(Throwable throwable, Map<String, AudioProcessor> map);\n    }\n\n    public LingoRecorder sampleRate(int sampleRate) {\n        recorderProperty.setSampleRate(sampleRate);\n        return this;\n    }\n\n    public LingoRecorder channels(int channels) {\n        recorderProperty.setChannels(channels);\n        return this;\n    }\n\n    public LingoRecorder bitsPerSample(int bitsPerSample) {\n        recorderProperty.setBitsPerSample(bitsPerSample);\n        return this;\n    }\n\n    public RecorderProperty getRecorderProperty() {\n        return recorderProperty;\n    }\n\n    public LingoRecorder wavFile(String filePath) {\n        this.wavFilePath = filePath;\n        return this;\n    }\n\n    private static class InternalRecorder implements Runnable {\n\n        private volatile boolean shouldRun;\n        private volatile boolean cancel;\n        private volatile Throwable processorsError;\n\n        private Thread thread;\n        private IRecorder recorder;\n        private Collection<AudioProcessor> audioProcessors;\n        private Handler handler;\n        private String outputFilePath;\n        private IVolumeCalculator volumeCalculator;\n\n        InternalRecorder(\n                IRecorder recorder,\n                String outputFilePath,\n                Collection<AudioProcessor> audioProcessors,\n                Handler handler,\n                IVolumeCalculator volumeCalculator) {\n            thread = new Thread(this);\n            this.audioProcessors = audioProcessors;\n            this.handler = handler;\n            this.recorder = recorder;\n            this.outputFilePath = outputFilePath;\n            this.volumeCalculator = volumeCalculator;\n        }\n\n        void cancel() {\n            shouldRun = false;\n            cancel = true;\n        }\n\n        void stop() {\n            shouldRun = false;\n        }\n\n        void start() {\n            thread.start();\n        }\n\n        @Override\n        public void run() {\n            shouldRun = true;\n\n            WavProcessor wavProcessor = null;\n            Throwable recordException = null;\n            ProcessThread processThread = null;\n\n            try {\n                int buffSize = recorder.getBufferSize();\n                byte[] bytes = new byte[buffSize];\n\n                processThread = new ProcessThread();\n                processThread.start();\n\n                recorder.startRecording();\n\n                if (outputFilePath != null) {\n                    wavProcessor = new WavProcessor(outputFilePath, recorder.getRecordProperty());\n                    wavProcessor.start();\n                }\n                while (shouldRun) {\n                    int result = recorder.read(bytes, buffSize);\n                    LOG.d(\"read buffer result = \" + result);\n                    if (result > 0) {\n                        if (volumeCalculator != null) {\n                            final long startCalculateTime = System.currentTimeMillis();\n                            final double volume = volumeCalculator.onAudioChunk(bytes,\n                                    result, recorder.getRecordProperty().getBitsPerSample());\n                            final long calculateDuration = System.currentTimeMillis() - startCalculateTime;\n                            LOG.d(\"duration of calculating chunk volume: \" + calculateDuration);\n                            handler.sendMessage(handler.obtainMessage(MESSAGE_VOLUME, volume));\n                        }\n\n                        processThread.process(bytes, result);\n\n                        if (wavProcessor != null) {\n                            wavProcessor.flow(bytes, result);\n                        }\n                    } else if (result < 0) {\n                        LOG.d(\"exit read from recorder result = \" + result);\n                        shouldRun = false;\n                        break;\n                    }\n                }\n                if (wavProcessor != null) {\n                    wavProcessor.end();\n                }\n            } catch (Throwable e) {\n                LOG.e(e);\n                recordException = e;\n            } finally {\n                shouldRun = false;\n\n                if (wavProcessor != null) {\n                    wavProcessor.release();\n                }\n\n                recorder.release();\n\n                // notify recorder stop\n                Message message = Message.obtain();\n                message.what = MESSAGE_RECORD_STOP;\n                Bundle bundle = new Bundle();\n                bundle.putLong(KEY_DURATION, recorder.getDurationInMills());\n                bundle.putString(KEY_FILEPATH, outputFilePath);\n                message.setData(bundle);\n                message.obj = recordException;\n                handler.sendMessage(message);\n\n                if (recordException != null) {\n                    cancel = true;\n                }\n\n                // try to end processor thread\n                if (processThread != null) {\n                    processThread.end(cancel);\n                }\n\n                // notify processor stop\n                Message msg = Message.obtain();\n                msg.what = MESSAGE_PROCESS_STOP;\n                if (recordException != null) {\n                    msg.obj = new RecordErrorCancelProcessingException(processorsError);\n                } else {\n                    msg.obj = processorsError;\n                }\n                handler.sendMessage(msg);\n            }\n        }\n\n        class ProcessThread extends Thread {\n\n            private LinkedBlockingQueue<Object> processorQueue;\n\n            ProcessThread() {\n                this(new LinkedBlockingQueue<>());\n            }\n\n            ProcessThread(final LinkedBlockingQueue<Object> processorQueue) {\n                super(\"processThread\");\n                this.processorQueue = processorQueue;\n            }\n\n            void process(@NonNull byte[] bytes, int buffSize) throws InterruptedException {\n                WrapBuffer wrapBuffer = new WrapBuffer();\n                wrapBuffer.setBytes(Arrays.copyOf(bytes, bytes.length));\n                wrapBuffer.setSize(buffSize);\n                processorQueue.put(wrapBuffer);\n            }\n\n            void end(boolean cancel) {\n                try {\n                    processorQueue.put(\"end\");\n                    if (cancel) {\n                        interrupt();\n                    }\n                    join();\n                    LOG.d(\"processorThread end\");\n                } catch (InterruptedException e) {\n                    e.printStackTrace();\n                }\n            }\n\n            @Override\n            public void run() {\n                super.run();\n                Object value;\n                try {\n                    for (AudioProcessor audioProcessor : audioProcessors) {\n                        checkIfNeedCancel();\n                        audioProcessor.start();\n                    }\n                    while ((value = processorQueue.take()) != null) {\n                        if (value instanceof WrapBuffer) {\n                            for (AudioProcessor audioProcessor : audioProcessors) {\n                                checkIfNeedCancel();\n                                WrapBuffer wrapBuffer = (WrapBuffer) value;\n                                audioProcessor.flow(wrapBuffer.getBytes(), wrapBuffer.getSize());\n                            }\n\n                            for (AudioProcessor audioProcessor : audioProcessors) {\n                                checkIfNeedCancel();\n                                if (audioProcessor.needExit()) {\n                                    LOG.d(String.format(\"exit because %s\", audioProcessor));\n                                    shouldRun = false;\n                                    break;\n                                }\n                            }\n                        } else {\n                            break;\n                        }\n                    }\n                    for (AudioProcessor audioProcessor : audioProcessors) {\n                        checkIfNeedCancel();\n                        audioProcessor.end();\n                    }\n                } catch (InterruptedException e) {\n                    processorsError = new CancelProcessingException(e);\n                } catch (Throwable e) {\n                    processorsError = e;\n                    LOG.e(e);\n                } finally {\n                    shouldRun = false;\n                    for (AudioProcessor audioProcessor : audioProcessors) {\n                        audioProcessor.release();\n                    }\n                }\n            }\n        }\n\n        private void checkIfNeedCancel() {\n            if (cancel) {\n                throw new CancelProcessingException();\n            }\n        }\n    }\n\n    private static class RecorderHandler extends Handler {\n\n        private LingoRecorder mLingoRecorder;\n        private Map<String, AudioProcessor> mAudioProcessorMap;\n\n        RecorderHandler(LingoRecorder lingoRecorder, Map<String, AudioProcessor> audioProcessorMap) {\n            super(Looper.getMainLooper());\n            mLingoRecorder = lingoRecorder;\n            mAudioProcessorMap = audioProcessorMap;\n        }\n\n        @Override\n        public void handleMessage(Message msg) {\n            super.handleMessage(msg);\n\n            switch (msg.what) {\n                case MESSAGE_RECORD_STOP:\n                    mLingoRecorder.internalRecorder = null;\n                    handleRecordStop(msg);\n                    break;\n                case MESSAGE_PROCESS_STOP:\n                    mLingoRecorder.available = true;\n                    mLingoRecorder.isProcessing = false;\n                    handleProcessStop(msg);\n                    break;\n                case MESSAGE_VOLUME:\n                    if (mLingoRecorder.onVolumeListener != null) {\n                        mLingoRecorder.onVolumeListener.onVolume((Double) msg.obj);\n                    }\n                    break;\n            }\n        }\n\n        private void handleRecordStop(Message msg) {\n            long durationInMills = msg.getData().getLong(KEY_DURATION, -1);\n            String outputFilePath = msg.getData().getString(KEY_FILEPATH);\n            if (mLingoRecorder.onRecordStopListener != null) {\n                OnRecordStopListener.Result result = new OnRecordStopListener.Result();\n                result.durationInMills = durationInMills;\n                result.outputFilePath = outputFilePath;\n                mLingoRecorder.onRecordStopListener.onRecordStop((Throwable) msg.obj, result);\n            }\n            LOG.d(\"record end\");\n        }\n\n        private void handleProcessStop(Message msg) {\n            if (mLingoRecorder.onProcessStopListener != null) {\n                mLingoRecorder.onProcessStopListener.onProcessStop((Throwable) msg.obj, mAudioProcessorMap);\n            }\n            LOG.d(\"process end\");\n        }\n    }\n\n    public static class CancelProcessingException extends RuntimeException {\n\n        public CancelProcessingException() {\n            super(\"cancel processing\");\n        }\n\n        public CancelProcessingException(Throwable throwable) {\n            super(throwable);\n        }\n    }\n\n    public static class RecordErrorCancelProcessingException extends CancelProcessingException {\n\n        public RecordErrorCancelProcessingException(Throwable throwable) {\n            super(throwable);\n        }\n    }\n\n    public void setDebugEnable(boolean enable) {\n        LOG.isEnable = enable;\n    }\n}\n"
  },
  {
    "path": "library/src/main/java/com/liulishuo/engzo/lingorecorder/processor/AudioProcessor.java",
    "content": "package com.liulishuo.engzo.lingorecorder.processor;\n\n/**\n * Created by wcw on 3/28/17.\n */\n\npublic interface AudioProcessor {\n\n    void start() throws Exception;\n\n    void flow(byte[] bytes, int size) throws Exception;\n\n    boolean needExit();\n\n    void end() throws Exception;\n\n    void release();\n\n}\n"
  },
  {
    "path": "library/src/main/java/com/liulishuo/engzo/lingorecorder/processor/TimerProcessor.java",
    "content": "package com.liulishuo.engzo.lingorecorder.processor;\n\nimport com.liulishuo.engzo.lingorecorder.utils.RecorderProperty;\n\npublic class TimerProcessor implements AudioProcessor {\n\n    private long mTimeInMills;\n\n    private RecorderProperty mRecorderProperty;\n\n    private long payloadSize = 0L;\n\n    public TimerProcessor(long timeInMills) {\n        this(new RecorderProperty(), timeInMills);\n    }\n\n    public TimerProcessor(RecorderProperty recorderProperty, long timeInMills) {\n        mRecorderProperty = recorderProperty;\n        mTimeInMills = timeInMills;\n    }\n\n    @Override\n    public void start() {\n        payloadSize = 0;\n    }\n\n    @Override\n    public void flow(byte[] bytes, int size) {\n        payloadSize += size;\n    }\n\n    @Override\n    public boolean needExit() {\n        long payloadSizeInBits = payloadSize * 8;\n        long durationInMills = (long)\n                (payloadSizeInBits * 1000.0 / mRecorderProperty.getBitsPerSample()\n                        / mRecorderProperty.getSampleRate() / mRecorderProperty.getChannels());\n        return durationInMills >= mTimeInMills;\n    }\n\n    @Override\n    public void end() {\n\n    }\n\n    @Override\n    public void release() {\n\n    }\n}"
  },
  {
    "path": "library/src/main/java/com/liulishuo/engzo/lingorecorder/processor/WavProcessor.java",
    "content": "package com.liulishuo.engzo.lingorecorder.processor;\n\nimport com.liulishuo.engzo.lingorecorder.utils.RecorderProperty;\n\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.RandomAccessFile;\n\n/**\n * Created by wcw on 3/28/17.\n */\n\npublic class WavProcessor implements AudioProcessor {\n\n    private String filePath;\n    private RandomAccessFile writer;\n    private int payloadSize = 0;\n\n    private RecorderProperty recordProperty;\n\n    public WavProcessor(String filePath) {\n        this(filePath, new RecorderProperty());\n    }\n\n    public WavProcessor(String filePath, RecorderProperty recordProperty) {\n        this.filePath = filePath;\n        this.recordProperty = recordProperty;\n    }\n\n    @Override\n    public void start() throws Exception {\n        payloadSize = 0;\n        // http://soundfile.sapp.org/doc/WaveFormat/\n        try {\n            writer = new RandomAccessFile(filePath, \"rw\");\n        } catch (FileNotFoundException ex) {\n            // Maybe the parent directory doesn't exist? Try creating it first.\n            new File(filePath).getParentFile().mkdirs();\n            writer = new RandomAccessFile(filePath, \"rw\");\n        }\n        writer.setLength(0); // Set file length to 0, to prevent unexpected behavior in case the file already existed\n        writer.writeBytes(\"RIFF\");\n        writer.writeInt(0); // Final file size not known yet, write 0\n        writer.writeBytes(\"WAVE\");\n        writer.writeBytes(\"fmt \");\n        writer.writeInt(Integer.reverseBytes(16)); // Sub-chunk size, 16 for PCM\n        writer.writeShort(Short.reverseBytes((short) 1)); // AudioFormat, 1 for PCM\n        writer.writeShort(Short.reverseBytes(\n                (short) recordProperty.getChannels()));// Number of channels, 1 for mono, 2 for\n        // stereo\n        writer.writeInt(Integer.reverseBytes(recordProperty.getSampleRate())); // Sample rate\n        writer.writeInt(Integer.reverseBytes(\n                recordProperty.getSampleRate() * recordProperty.getChannels()\n                        * recordProperty.getBitsPerSample()\n                        / 8)); // Byte rate, SampleRate*NumberOfChannels*bitsPerSample/8\n        writer.writeShort(Short.reverseBytes(\n                (short) (recordProperty.getChannels() * recordProperty.getBitsPerSample()\n                        / 8))); // Block align, NumberOfChannels*bitsPerSample/8\n        writer.writeShort(\n                Short.reverseBytes((short) recordProperty.getBitsPerSample())); // Bits per sample\n        writer.writeBytes(\"data\");\n        writer.writeInt(0); // Data chunk size not known yet, write 0\n\n    }\n\n    @Override\n    public void flow(byte[] bytes, int result) throws Exception {\n        if (result > 0)  {\n            writer.write(bytes);\n            payloadSize += result;\n        }\n    }\n\n    @Override\n    public boolean needExit() {\n        return false;\n    }\n\n    @Override\n    public void end() throws Exception {\n        writer.seek(4); // Write size to RIFF header\n        writer.writeInt(Integer.reverseBytes(36 + payloadSize));\n\n        writer.seek(40); // Write size to Subchunk2Size field\n        writer.writeInt(Integer.reverseBytes(payloadSize));\n    }\n\n    @Override\n    public void release() {\n        try {\n            if (writer != null) {\n                writer.close();\n                writer = null;\n            }\n        } catch (Exception ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    public String getFilePath() {\n        return filePath;\n    }\n\n    public RecorderProperty getRecordProperty() {\n        return recordProperty;\n    }\n}\n"
  },
  {
    "path": "library/src/main/java/com/liulishuo/engzo/lingorecorder/recorder/AndroidRecorder.java",
    "content": "package com.liulishuo.engzo.lingorecorder.recorder;\n\nimport android.media.AudioFormat;\nimport android.media.AudioRecord;\nimport android.media.MediaRecorder;\n\nimport androidx.annotation.NonNull;\n\nimport com.liulishuo.engzo.lingorecorder.recorder.exception.RecorderException;\nimport com.liulishuo.engzo.lingorecorder.recorder.exception.RecorderGetBufferSizeException;\nimport com.liulishuo.engzo.lingorecorder.recorder.exception.RecorderInitException;\nimport com.liulishuo.engzo.lingorecorder.recorder.exception.RecorderReadException;\nimport com.liulishuo.engzo.lingorecorder.recorder.exception.RecorderStartException;\nimport com.liulishuo.engzo.lingorecorder.utils.RecorderProperty;\n\n/**\n * Created by wcw on 4/5/17.\n */\n\npublic class AndroidRecorder implements IRecorder {\n\n    private int audioFormat;\n    private long payloadSize;\n    private int channels;\n    private AudioRecord recorder;\n\n    private final RecorderProperty recorderProperty;\n\n    public AndroidRecorder(final RecorderProperty recorderProperty) {\n        this.recorderProperty = recorderProperty;\n        if (this.recorderProperty.getBitsPerSample() == 16) {\n            audioFormat = AudioFormat.ENCODING_PCM_16BIT;\n        } else if (this.recorderProperty.getBitsPerSample() == 8) {\n            audioFormat = AudioFormat.ENCODING_PCM_8BIT;\n        } else {\n            throw new RecorderException(\n                    \"unsupported bitsPerSample: \" + this.recorderProperty.getBitsPerSample());\n        }\n        if (this.recorderProperty.getChannels() == 1) {\n            this.channels = AudioFormat.CHANNEL_IN_MONO;\n        } else if (this.recorderProperty.getChannels() == 2) {\n            this.channels = AudioFormat.CHANNEL_IN_STEREO;\n        } else {\n            throw new RecorderException(\n                    \"unsupported channel: \" + this.recorderProperty.getChannels());\n        }\n    }\n\n    @Override\n    public int getBufferSize() {\n        int ret = AudioRecord.getMinBufferSize(recorderProperty.getSampleRate(), channels,\n                audioFormat);\n        if (ret > 0) {\n            return 2 * ret;\n        } else {\n            throw new RecorderGetBufferSizeException(ret);\n        }\n    }\n\n    @Override\n    public void startRecording() throws Exception {\n        int buffSize = getBufferSize();\n\n        recorder = new AudioRecord(MediaRecorder.AudioSource.MIC, recorderProperty.getSampleRate(),\n                channels, audioFormat, buffSize);\n\n        if (recorder.getState() != AudioRecord.STATE_INITIALIZED) {\n            throw new RecorderInitException();\n        }\n\n        payloadSize = 0;\n        recorder.startRecording();\n\n        if (recorder.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING) {\n            throw new RecorderStartException();\n        }\n    }\n\n    @Override\n    public int read(@NonNull byte[] bytes, int buffSize) throws Exception {\n        int read = recorder.read(bytes, 0, buffSize);\n        if (read < 0) {\n            throw new RecorderReadException(read);\n        }\n        payloadSize += read;\n        return read;\n    }\n\n    @Override\n    public void release() {\n        if (recorder != null) {\n            recorder.release();\n        }\n    }\n\n    @Override\n    public long getDurationInMills() {\n        return (long) (payloadSize * 8.0 * 1000 / recorderProperty.getBitsPerSample()\n                / recorderProperty.getSampleRate() / recorderProperty.getChannels());\n    }\n\n    @Override\n    public RecorderProperty getRecordProperty() {\n        return recorderProperty;\n    }\n}\n"
  },
  {
    "path": "library/src/main/java/com/liulishuo/engzo/lingorecorder/recorder/IRecorder.java",
    "content": "package com.liulishuo.engzo.lingorecorder.recorder;\n\n\nimport androidx.annotation.NonNull;\n\nimport com.liulishuo.engzo.lingorecorder.utils.RecorderProperty;\n\n/**\n * Created by wcw on 4/5/17.\n */\n\npublic interface IRecorder {\n\n    int getBufferSize() throws Throwable;\n\n    void startRecording() throws Throwable;\n\n    int read(@NonNull byte[] bytes, int buffSize) throws Throwable;\n\n    void release();\n\n    long getDurationInMills();\n\n    RecorderProperty getRecordProperty();\n}\n"
  },
  {
    "path": "library/src/main/java/com/liulishuo/engzo/lingorecorder/recorder/WavFileRecorder.java",
    "content": "package com.liulishuo.engzo.lingorecorder.recorder;\n\nimport androidx.annotation.NonNull;\n\nimport com.liulishuo.engzo.lingorecorder.utils.LOG;\nimport com.liulishuo.engzo.lingorecorder.utils.RecorderProperty;\n\nimport java.io.FileInputStream;\n\n/**\n * Created by wcw on 4/5/17.\n */\n\npublic class WavFileRecorder implements IRecorder {\n\n    private FileInputStream fis;\n    private long payloadSize;\n\n    private final String filePath;\n    private final RecorderProperty recorderProperty;\n\n    public WavFileRecorder(String filePath, RecorderProperty recorderProperty) {\n        this.filePath = filePath;\n        this.recorderProperty = recorderProperty;\n    }\n\n    @Override\n    public int getBufferSize() {\n        return 1024;\n    }\n\n    @Override\n    public void startRecording() throws Exception {\n        fis = new FileInputStream(filePath);\n        long skip = fis.skip(44);\n        LOG.d(\"skip size = \" + skip);\n        payloadSize = 0;\n    }\n\n    @Override\n    public int read(@NonNull byte[] bytes, int buffSize) throws Exception {\n        int count = fis.read(bytes, 0, buffSize);\n        payloadSize += count;\n        return count;\n    }\n\n    @Override\n    public void release() {\n        try {\n            fis.close();\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    @Override\n    public long getDurationInMills() {\n        return (long) (payloadSize * 8.0 * 1000 / recorderProperty.getBitsPerSample()\n                / recorderProperty.getSampleRate() / recorderProperty.getChannels());\n    }\n\n    @Override\n    public RecorderProperty getRecordProperty() {\n        return recorderProperty;\n    }\n}\n"
  },
  {
    "path": "library/src/main/java/com/liulishuo/engzo/lingorecorder/recorder/exception/RecorderException.java",
    "content": "package com.liulishuo.engzo.lingorecorder.recorder.exception;\n\n/**\n * Created by wcw on 1/26/18.\n */\n\npublic class RecorderException extends RuntimeException {\n\n    public RecorderException(String message) {\n        super((message));\n    }\n}\n"
  },
  {
    "path": "library/src/main/java/com/liulishuo/engzo/lingorecorder/recorder/exception/RecorderGetBufferSizeException.java",
    "content": "package com.liulishuo.engzo.lingorecorder.recorder.exception;\n\n/**\n * Created by wcw on 1/26/18.\n */\n\npublic class RecorderGetBufferSizeException extends RecorderException {\n\n    public RecorderGetBufferSizeException(int error) {\n        super(\"recorder get buffer size error \" + error);\n    }\n}\n"
  },
  {
    "path": "library/src/main/java/com/liulishuo/engzo/lingorecorder/recorder/exception/RecorderInitException.java",
    "content": "package com.liulishuo.engzo.lingorecorder.recorder.exception;\n\n/**\n * Created by wcw on 1/26/18.\n */\n\npublic class RecorderInitException extends RecorderException {\n\n    public RecorderInitException() {\n        super(\"init Android audioRecorder error\");\n    }\n}\n"
  },
  {
    "path": "library/src/main/java/com/liulishuo/engzo/lingorecorder/recorder/exception/RecorderReadException.java",
    "content": "package com.liulishuo.engzo.lingorecorder.recorder.exception;\n\n/**\n * Created by wcw on 1/26/18.\n */\n\npublic class RecorderReadException extends RecorderException {\n\n    public RecorderReadException(int error) {\n        super(\"recorder read error \" + error);\n    }\n}\n"
  },
  {
    "path": "library/src/main/java/com/liulishuo/engzo/lingorecorder/recorder/exception/RecorderStartException.java",
    "content": "package com.liulishuo.engzo.lingorecorder.recorder.exception;\n\n/**\n * Created by wcw on 1/26/18.\n */\n\npublic class RecorderStartException extends RecorderException {\n\n    public RecorderStartException() {\n        super(\"start Android audioRecorder error\");\n    }\n}\n"
  },
  {
    "path": "library/src/main/java/com/liulishuo/engzo/lingorecorder/utils/LOG.java",
    "content": "package com.liulishuo.engzo.lingorecorder.utils;\n\nimport android.text.TextUtils;\nimport android.util.Log;\n\n/**\n * Created by wcw on 3/28/17.\n */\n\npublic class LOG {\n\n    public static boolean isEnable = false;\n\n    public static final String TAG = \"LingoRecorder\";\n\n    public static void d(String log) {\n        if (isEnable && !TextUtils.isEmpty(log)) {\n            Log.d(TAG, log);\n        }\n    }\n\n    public static void e(Throwable throwable) {\n        if (isEnable && throwable != null) {\n            Log.e(TAG, Log.getStackTraceString(throwable));\n        }\n    }\n\n    public static void e(String message) {\n        if (isEnable && !TextUtils.isEmpty(message)) {\n            Log.e(TAG, message);\n        }\n    }\n}\n"
  },
  {
    "path": "library/src/main/java/com/liulishuo/engzo/lingorecorder/utils/RecorderProperty.java",
    "content": "package com.liulishuo.engzo.lingorecorder.utils;\n\n/**\n * Created by rantianhua on 17/8/29.\n * hold properties for a recorder\n */\n\npublic class RecorderProperty {\n\n    private int sampleRate;\n    private int channels;\n    private int bitsPerSample;\n\n    public RecorderProperty() {\n        setSampleRate(16000);\n        setChannels((short) 1);\n        setBitsPerSample(16);\n    }\n\n    public int getBitsPerSample() {\n        return bitsPerSample;\n    }\n\n    public RecorderProperty setBitsPerSample(int bitsPerSample) {\n        this.bitsPerSample = bitsPerSample;\n        return this;\n    }\n\n    public int getSampleRate() {\n        return sampleRate;\n    }\n\n    public RecorderProperty setSampleRate(int sampleRate) {\n        this.sampleRate = sampleRate;\n        return this;\n    }\n\n    public int getChannels() {\n        return channels;\n    }\n\n    public RecorderProperty setChannels(int channels) {\n        this.channels = channels;\n        return this;\n    }\n}\n"
  },
  {
    "path": "library/src/main/java/com/liulishuo/engzo/lingorecorder/utils/WrapBuffer.java",
    "content": "package com.liulishuo.engzo.lingorecorder.utils;\n\npublic class WrapBuffer {\n\n    private byte[] bytes;\n    private int size;\n\n    public byte[] getBytes() {\n        return bytes;\n    }\n\n    public void setBytes(byte[] bytes) {\n        this.bytes = bytes;\n    }\n\n    public int getSize() {\n        return size;\n    }\n\n    public void setSize(int size) {\n        this.size = size;\n    }\n}"
  },
  {
    "path": "library/src/main/java/com/liulishuo/engzo/lingorecorder/volume/DefaultVolumeCalculator.java",
    "content": "package com.liulishuo.engzo.lingorecorder.volume;\n\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\n\n/**\n * Created by rantianhua on 2017/9/26.\n * provide a default volume calculator\n */\n\npublic class DefaultVolumeCalculator implements IVolumeCalculator {\n\n    /**\n     *\n     * @param chunk record chunk\n     * @param size size of chunk\n     * @param bitsPerSample bits per sample\n     * @return the volume decibels 0 - 90\n     */\n    @Override\n    public double onAudioChunk(byte[] chunk, int size, int bitsPerSample) {\n        double sumVolume = 0.0;\n        double avgVolume;\n        if (bitsPerSample == 16) {\n            final ByteBuffer byteBuffer = ByteBuffer.wrap(chunk, 0, size);\n            final short[] buf = new short[size / 2];\n            byteBuffer.order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(buf);\n            for (short b : buf) {\n                sumVolume += Math.abs(b);\n            }\n            avgVolume = sumVolume / buf.length;\n        } else {\n            for (int i = 0; i < size; i++) {\n                sumVolume += Math.abs(chunk[i]);\n            }\n            avgVolume = sumVolume / size;\n        }\n        return 20 * Math.log10(avgVolume);\n    }\n}\n"
  },
  {
    "path": "library/src/main/java/com/liulishuo/engzo/lingorecorder/volume/IVolumeCalculator.java",
    "content": "package com.liulishuo.engzo.lingorecorder.volume;\n\n/**\n * Created by rantianhua on 2017/9/26.\n * calculate volume\n */\n\npublic interface IVolumeCalculator {\n\n    double onAudioChunk(byte[] chunk, int size, int bitsPerSample);\n}\n"
  },
  {
    "path": "library/src/main/java/com/liulishuo/engzo/lingorecorder/volume/OnVolumeListener.java",
    "content": "package com.liulishuo.engzo.lingorecorder.volume;\n\n/**\n * Created by rantianhua on 2017/9/26.\n * the callback of volume\n */\n\npublic interface OnVolumeListener {\n\n    void onVolume(double volume);\n\n}\n"
  },
  {
    "path": "library/src/test/java/com/liulishuo/engzo/lingorecorder/ExampleUnitTest.java",
    "content": "package com.liulishuo.engzo.lingorecorder;\n\nimport org.junit.Test;\n\nimport static org.junit.Assert.*;\n\n/**\n * Example local unit test, which will execute on the development machine (host).\n *\n * @see <a href=\"http://d.android.com/tools/testing\">Testing documentation</a>\n */\npublic class ExampleUnitTest {\n    @Test\n    public void addition_isCorrect() throws Exception {\n        assertEquals(4, 2 + 2);\n    }\n}"
  },
  {
    "path": "settings.gradle",
    "content": "include ':demo' , ':lingo-recorder'\n\nproject(':lingo-recorder').projectDir = new File(settingsDir, 'library')\n\n"
  }
]