├── .gitignore ├── .gitmodules ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── RESOURCES.md ├── SimpleSynth ├── README.md ├── app │ ├── CMakeLists.txt │ ├── build.gradle │ ├── proguard-rules.pro │ └── src │ │ └── main │ │ ├── AndroidManifest.xml │ │ ├── cpp │ │ ├── OpenSLES_Android_API24.h │ │ ├── android_log.h │ │ ├── audio_common.cc │ │ ├── audio_common.h │ │ ├── audio_player.cc │ │ ├── audio_player.h │ │ ├── audio_renderer.h │ │ ├── cpu_relax.h │ │ ├── jni_bridge.cc │ │ ├── load_stabilizer.cc │ │ ├── load_stabilizer.h │ │ ├── synthesizer.cc │ │ ├── synthesizer.h │ │ ├── trace.cc │ │ └── trace.h │ │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── simplesynth │ │ │ └── MainActivity.java │ │ └── res │ │ ├── layout │ │ └── activity_main.xml │ │ ├── mipmap-hdpi │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ └── ic_launcher.png │ │ ├── values-w820dp │ │ └── dimens.xml │ │ └── values │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml ├── build.gradle ├── gradle.properties ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── screenshot.png └── settings.gradle ├── aaudio ├── .google │ └── packaging.yaml ├── README.md ├── build.gradle ├── common │ ├── audio_common.cpp │ └── audio_common.h ├── echo-screenshot.png ├── echo │ ├── build.gradle │ ├── proguard-rules.pro │ └── src │ │ └── main │ │ ├── AndroidManifest.xml │ │ ├── cpp │ │ ├── AudioEffect.cpp │ │ ├── AudioEffect.h │ │ ├── CMakeLists.txt │ │ ├── EchoAudioEngine.cpp │ │ ├── EchoAudioEngine.h │ │ ├── jni_bridge.cpp │ │ └── ndk-stl-config.cmake │ │ ├── java │ │ └── com │ │ │ └── google │ │ │ └── sample │ │ │ └── aaudio │ │ │ └── echo │ │ │ ├── EchoEngine.java │ │ │ └── MainActivity.java │ │ └── res │ │ ├── layout │ │ └── activity_main.xml │ │ ├── mipmap-hdpi │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ └── ic_launcher.png │ │ ├── values-v21 │ │ └── styles.xml │ │ ├── values-w820dp │ │ └── dimens.xml │ │ └── values │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml ├── gradle.properties ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── hello-aaudio-screenshot.png ├── hello-aaudio │ ├── build.gradle │ ├── proguard-rules.pro │ └── src │ │ └── main │ │ ├── AndroidManifest.xml │ │ ├── cpp │ │ ├── CMakeLists.txt │ │ ├── PlayAudioEngine.cpp │ │ ├── PlayAudioEngine.h │ │ ├── SineGenerator.h │ │ ├── jni_bridge.cpp │ │ └── ndk-stl-config.cmake │ │ ├── java │ │ └── com │ │ │ └── google │ │ │ └── sample │ │ │ └── aaudio │ │ │ └── play │ │ │ ├── MainActivity.java │ │ │ └── PlaybackEngine.java │ │ └── res │ │ ├── layout │ │ ├── activity_main.xml │ │ └── buffer_sizes_spinner.xml │ │ ├── mipmap-hdpi │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ └── ic_launcher.png │ │ ├── values-v21 │ │ └── styles.xml │ │ ├── values-w820dp │ │ └── dimens.xml │ │ └── values │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml └── settings.gradle ├── audio-device ├── .gitignore ├── README.md ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── google │ │ └── sample │ │ └── audio_device │ │ ├── AudioDeviceAdapter.java │ │ ├── AudioDeviceInfoConverter.java │ │ ├── AudioDeviceListEntry.java │ │ └── AudioDeviceSpinner.java │ └── res │ ├── layout │ └── audio_devices.xml │ └── values │ ├── dimens.xml │ └── strings.xml ├── debug-utils ├── logging_macros.h ├── trace.cpp └── trace.h ├── djdroid-light.png └── oboe └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | *.iml 3 | .externalNativeBuild 4 | .gradle 5 | .idea 6 | local.properties 7 | .DS_Store 8 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "oboe/hello-oboe/src/main/cpp/oboe"] 2 | path = oboe/hello-oboe/src/main/cpp/oboe 3 | url = sso://devrel/libraries/android/oboe 4 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to become a contributor and submit your own code 2 | 3 | ## Contributor License Agreements 4 | 5 | We'd love to accept your sample apps and patches! Before we can take them, we 6 | have to jump a couple of legal hurdles. 7 | 8 | Please fill out either the individual or corporate Contributor License Agreement 9 | (CLA). 10 | 11 | * If you are an individual writing original source code and you're sure you 12 | own the intellectual property, then you'll need to sign an [individual CLA] 13 | (http://code.google.com/legal/individual-cla-v1.0.html). 14 | * If you work for a company that wants to allow you to contribute your work, 15 | then you'll need to sign a [corporate CLA] 16 | (http://code.google.com/legal/corporate-cla-v1.0.html). 17 | 18 | Follow either of the two links above to access the appropriate CLA and 19 | instructions for how to sign and return it. Once we receive it, we'll be able to 20 | accept your pull requests. 21 | 22 | ## Contributing a Patch 23 | 24 | 1. Sign a Contributor License Agreement, if you have not yet done so (see 25 | details above). 26 | 1. Create your change to the repo in question. 27 | * Fork the desired repo, develop and test your code changes. 28 | * Ensure that your code is clear and comprehensible. 29 | * Ensure that your code has an appropriate set of unit tests which all pass. 30 | 1. Submit a pull request. 31 | 1. The repo owner will review your request. If it is approved, the change will 32 | be merged. If it needs additional work, the repo owner will respond with 33 | useful comments. 34 | 35 | ## Contributing a New Sample App 36 | 37 | 1. Sign a Contributor License Agreement, if you have not yet done so (see 38 | details above). 39 | 1. Create your own repo for your app following this naming convention: 40 | * mirror-{app-name}-{language or plaform} 41 | * apps: quickstart, photohunt-server, photohunt-client 42 | * example: mirror-quickstart-android 43 | * For multi-language apps, concatenate the primary languages like this: 44 | mirror-photohunt-server-java-python. 45 | 46 | 1. Create your sample app in this repo. 47 | * Be sure to clone the README.md, CONTRIBUTING.md and LICENSE files from the 48 | googlecast repo. 49 | * Ensure that your code is clear and comprehensible. 50 | * Ensure that your code has an appropriate set of unit tests which all pass. 51 | * Instructional value is the top priority when evaluating new app proposals for 52 | this collection of repos. 53 | 1. Submit a request to fork your repo in googlecast organization. 54 | 1. The repo owner will review your request. If it is approved, the sample will 55 | be merged. If it needs additional work, the repo owner will respond with 56 | useful comments. -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Android High Performance Audio Samples 2 | 3 | This sample has been deprecated/archived meaning it's read-only and it's no longer actively maintained (more details on archiving can be found [here][1]). 4 | 5 | For high performance audio, we recommend using the [Oboe library][2] for development. Thank you! 6 | 7 | [1]: https://help.github.com/en/articles/about-archiving-repositories 8 | [2]: https://github.com/google/oboe 9 | -------------------------------------------------------------------------------- /RESOURCES.md: -------------------------------------------------------------------------------- 1 | # Resources 2 | If you have a resource you would like to add, please [edit this page](edit/master/RESOURCES.md) and submit a pull request. 3 | 4 | ## Documentation 5 | - [High-performance audio guide](https://developer.android.com/ndk/guides/audio/index.html) 6 | - [Android Audio architecture](https://source.android.com/devices/audio/) 7 | 8 | ## Codelabs 9 | - [Making Waves Part 1 - Build a synthesizer for Android](https://codelabs.developers.google.com/codelabs/making-waves-1-synth) 10 | 11 | ## Latency Testing Apps 12 | 13 | - [WALT](https://github.com/google/walt) 14 | - Dr Rick O'Rang Loopback app ([source](https://github.com/gkasten/drrickorang/tree/master/LoopbackApp) | [binary](https://play.google.com/store/apps/details?id=org.drrickorang.loopback)) 15 | 16 | ## Other code samples 17 | - [Android NDK native-audio](https://github.com/googlesamples/android-ndk/tree/master/native-audio) - Uses OpenSL ES to show how to perform simple playback 18 | - [Android NDK audio-echo ](https://github.com/googlesamples/android-ndk/tree/master/audio-echo) - Uses OpenSL ES to demonstrate recording and playback 19 | - [Phil Burk's MIDI samples](https://github.com/philburk/android-midisuite) 20 | 21 | ## Videos 22 | 23 | - [Best Practices for Android Audio (Google I/O '17)](https://www.youtube.com/watch?v=C0BPXZIvG-Q) (19 May 2017) 24 | - [Whats New In Android Audio, Don Turner & Phil Burk (Android)](https://www.youtube.com/watch?v=dAyeEN21FbM) (17 Nov 2016) 25 | - [Android high-performance audio - Google I/O 2016](https://www.youtube.com/watch?v=F2ZDp-eNrh4) (19 May 2016) 26 | - [Developing Android Apps with High Performance Audio, JUCE Summit 2015](https://www.youtube.com/watch?v=vPc7zvfpUos) (18 Feb 2016) 27 | - [Audio latency: buffer sizes](https://www.youtube.com/watch?v=PnDK17zP9BI) (13 Jul 2015) 28 | - [Sample rates and resampling: Why can't we all just agree?](https://www.youtube.com/watch?v=6Dl6BdrA-sQ) (25 Jun 2014) 29 | - [Will it float? The glory and shame of floating-point audio](https://www.youtube.com/watch?v=sIcieUqMml8) (25 Jun 2014) 30 | - [Google I/O 2013 - High Performance Audio](https://www.youtube.com/watch?v=d3kfEeMZ65c) (18 May 2013) 31 | -------------------------------------------------------------------------------- /SimpleSynth/README.md: -------------------------------------------------------------------------------- 1 | Simple Synth 2 | === 3 | This sample app will play a 440Hz sine wave. It demonstrates how to: 4 | 5 | - Create a simple synthesizer which renders audio data to an OpenSL ES player 6 | - Set thread affinity on the OpenSL ES callback to avoid CPU core migrations 7 | - Stabilize a varying load to avoid audio glitches caused by CPU frequency scaling 8 | - Monitor underruns in real time (API 24+ only, see below for more info) 9 | 10 | Building 11 | -------- 12 | - Load this project into Android Studio 13 | - Hit the green 'Run' button to build and run Simple Synth on the Android emulator or 14 | attached Android device (must be API 21+) 15 | 16 | Instructions for use 17 | -------------------- 18 | There are 4 UI controls. Here's what they do: 19 | 20 | - Test tone: Toggles the synthesizer tone on and off 21 | - Variable load: Varies the load (number of computations) used to render the synthesizer audio data. 22 | Every 2 seconds the load will change from HIGH (100% of the chosen work cycles) to LOW (10% of the 23 | chosen number of work cycles). 24 | - Stabilized load: Only useful when variable load is on, will attempt to smooth out a varying load 25 | - Work cycles: Allows you to set the number of computations used to render the synthesizer audio 26 | data. 27 | 28 | Screenshots 29 | ----------- 30 | ![screenshot](screenshot.png) 31 | 32 | Notes 33 | ----- 34 | - Real time monitoring of audio underruns is only supported on API 24+ (the `AcquireJavaProxy` 35 | method was introduced in API 24+). If you are running this sample on an older API 36 | you can monitor underruns by running `adb shell dumpsys media.audio_flinger`. The underrun count of 37 | the audio output stream is shown in the `UndFrmCnt` column. 38 | 39 | 40 | License 41 | ------- 42 | Copyright 2017 Google, Inc. 43 | 44 | Licensed to the Apache Software Foundation (ASF) under one or more contributor 45 | license agreements. See the NOTICE file distributed with this work for 46 | additional information regarding copyright ownership. The ASF licenses this 47 | file to you under the Apache License, Version 2.0 (the "License"); you may not 48 | use this file except in compliance with the License. You may obtain a copy of 49 | the License at 50 | 51 | http://www.apache.org/licenses/LICENSE-2.0 52 | 53 | Unless required by applicable law or agreed to in writing, software 54 | distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 55 | WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 56 | License for the specific language governing permissions and limitations under 57 | the License. 58 | -------------------------------------------------------------------------------- /SimpleSynth/app/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # For more information about using CMake with Android Studio, read the 2 | # documentation: https://d.android.com/studio/projects/add-native-code.html 3 | 4 | # Sets the minimum version of CMake required to build the native library. 5 | 6 | cmake_minimum_required(VERSION 3.4.1) 7 | 8 | add_library( SimpleSynth SHARED 9 | src/main/cpp/jni_bridge.cc 10 | src/main/cpp/audio_player.cc 11 | src/main/cpp/synthesizer.cc 12 | src/main/cpp/load_stabilizer.cc 13 | src/main/cpp/trace.cc 14 | src/main/cpp/audio_common.cc 15 | ) 16 | 17 | target_link_libraries( SimpleSynth 18 | log OpenSLES android) 19 | -------------------------------------------------------------------------------- /SimpleSynth/app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | 4 | android{ 5 | compileSdkVersion 28 6 | 7 | defaultConfig { 8 | minSdkVersion 21 9 | targetSdkVersion 26 10 | applicationId "com.example.simplesynth" 11 | versionName "3.0" 12 | versionCode 3 13 | externalNativeBuild { 14 | cmake { 15 | cppFlags "-std=c++11 -Werror" 16 | } 17 | } 18 | } 19 | signingConfigs { 20 | release { 21 | storeFile new File("${System.properties['user.home']}/.android/debug.keystore") 22 | storePassword 'android' 23 | storeType "jks" 24 | keyAlias 'androiddebugkey' 25 | keyPassword 'android' 26 | } 27 | } 28 | buildTypes { 29 | release { 30 | signingConfig signingConfigs.release 31 | minifyEnabled = false 32 | proguardFiles.add(file('proguard-rules.txt')) 33 | // Note: The following line may affect your compiler flags: see https://github.com/android-ndk/ndk/issues/699 34 | debuggable true 35 | } 36 | } 37 | externalNativeBuild { 38 | cmake { 39 | path "CMakeLists.txt" 40 | } 41 | } 42 | } 43 | 44 | dependencies { 45 | compile fileTree(dir: 'libs', include: ['*.jar']) 46 | compile 'com.android.support:appcompat-v7:28.0.0-rc02' 47 | } 48 | -------------------------------------------------------------------------------- /SimpleSynth/app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/donturner/Library/Android/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /SimpleSynth/app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 10 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /SimpleSynth/app/src/main/cpp/OpenSLES_Android_API24.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef SIMPLESYNTH_OPENSLES_ANDROID_API24_H 18 | #define SIMPLESYNTH_OPENSLES_ANDROID_API24_H 19 | 20 | #include 21 | #include 22 | #include 23 | 24 | /** Android Configuration interface methods */ 25 | struct SLAndroidConfigurationItfAPI24_; 26 | typedef const struct SLAndroidConfigurationItfAPI24_ * const * SLAndroidConfigurationItfAPI24; 27 | /* 28 | * Java Proxy Type IDs 29 | */ 30 | #define SL_ANDROID_JAVA_PROXY_ROUTING 0x0001 31 | 32 | struct SLAndroidConfigurationItfAPI24_ { 33 | SLresult (*SetConfiguration) (SLAndroidConfigurationItfAPI24 self, 34 | const SLchar *configKey, 35 | const void *pConfigValue, 36 | SLuint32 valueSize); 37 | SLresult (*GetConfiguration) (SLAndroidConfigurationItfAPI24 self, 38 | const SLchar *configKey, 39 | SLuint32 *pValueSize, 40 | void *pConfigValue 41 | ); 42 | SLresult (*AcquireJavaProxy) (SLAndroidConfigurationItfAPI24 self, 43 | SLuint32 proxyType, 44 | jobject *pProxyObj); 45 | SLresult (*ReleaseJavaProxy) (SLAndroidConfigurationItfAPI24 self, 46 | SLuint32 proxyType); 47 | }; 48 | 49 | #endif //SIMPLESYNTH_OPENSLES_ANDROID_API24_H 50 | -------------------------------------------------------------------------------- /SimpleSynth/app/src/main/cpp/android_log.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef SIMPLESYNTH_ANDROID_LOG_H 18 | #define SIMPLESYNTH_ANDROID_LOG_H 19 | 20 | #if 1 21 | 22 | #include 23 | 24 | #define MODULE_NAME "SimpleSynth" 25 | #define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, MODULE_NAME, __VA_ARGS__) 26 | #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, MODULE_NAME, __VA_ARGS__) 27 | #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, MODULE_NAME, __VA_ARGS__) 28 | #define LOGW(...) __android_log_print(ANDROID_LOG_WARN,MODULE_NAME, __VA_ARGS__) 29 | #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,MODULE_NAME, __VA_ARGS__) 30 | #define LOGF(...) __android_log_print(ANDROID_LOG_FATAL,MODULE_NAME, __VA_ARGS__) 31 | 32 | #else 33 | 34 | #define LOGV(...) 35 | #define LOGD(...) 36 | #define LOGI(...) 37 | #define LOGW(...) 38 | #define LOGE(...) 39 | #define LOGF(...) 40 | #endif 41 | 42 | #endif //SIMPLESYNTH_ANDROID_LOG_H 43 | -------------------------------------------------------------------------------- /SimpleSynth/app/src/main/cpp/audio_common.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include "audio_common.h" 18 | 19 | int64_t timestamp_to_nanos(timespec ts){ 20 | return (ts.tv_sec * (int64_t) NANOS_IN_SECOND) + ts.tv_nsec; 21 | } 22 | 23 | int64_t get_time(){ 24 | timespec ts; 25 | clock_gettime(CLOCK_MONOTONIC, &ts); 26 | return timestamp_to_nanos(ts); 27 | } 28 | -------------------------------------------------------------------------------- /SimpleSynth/app/src/main/cpp/audio_common.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef SIMPLESYNTH_AUDIO_COMMON_H 18 | #define SIMPLESYNTH_AUDIO_COMMON_H 19 | 20 | #include 21 | #include 22 | 23 | #define NANOS_IN_SECOND 1000000000 24 | 25 | #define SLASSERT(x) do {\ 26 | assert(SL_RESULT_SUCCESS == (x));\ 27 | (void) (x);\ 28 | } while (0) 29 | 30 | struct AudioStreamFormat { 31 | uint32_t frame_rate; 32 | uint32_t frames_per_buffer; 33 | uint16_t num_audio_channels; 34 | uint16_t num_buffers; 35 | }; 36 | 37 | int64_t timestamp_to_nanos(timespec ts); 38 | int64_t get_time(); 39 | 40 | #endif //SIMPLESYNTH_AUDIO_COMMON_H 41 | -------------------------------------------------------------------------------- /SimpleSynth/app/src/main/cpp/audio_player.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | #include 19 | #include 20 | #include 21 | 22 | #include 23 | 24 | #include "audio_player.h" 25 | #include "android_log.h" 26 | 27 | #define MILLIHERTZ_IN_HERTZ 1000 28 | #define JAVA_PROXY_AVAILABLE_FROM_API_LEVEL 24 29 | 30 | void SLPlayerCallback(SLAndroidSimpleBufferQueueItf buffer_queue_itf, void *context) { 31 | (static_cast(context))->processSLCallback(buffer_queue_itf); 32 | } 33 | 34 | AudioPlayer::AudioPlayer(SLEngineItf engine_itf, 35 | SLObjectItf output_mix_object_itf, 36 | AudioRenderer *renderer, 37 | AudioStreamFormat stream_format, 38 | int api_level) : 39 | renderer_(renderer), 40 | stream_format_(stream_format), 41 | is_thread_affinity_set_(false) { 42 | 43 | assert(renderer_ != nullptr); 44 | 45 | LOGV("Creating AudioPlayer with frame rate %d, " 46 | "frames per buffer %d, " 47 | "buffers %d", 48 | stream_format.frame_rate, 49 | stream_format.frames_per_buffer, 50 | stream_format.num_buffers); 51 | 52 | SLDataLocator_AndroidSimpleBufferQueue sl_data_locator_bufferqueue_source; 53 | SLDataFormat_PCM sl_data_format_pcm; 54 | SLDataSource sl_data_source; 55 | SLDataLocator_OutputMix sl_data_locator_output_mix; 56 | SLDataSink sl_data_sink; 57 | 58 | initAudioBuffer(stream_format_.frames_per_buffer, 59 | stream_format_.num_audio_channels, 60 | audio_buffer_); 61 | initDataLocatorBufferQueue((SLuint32) stream_format_.num_buffers, 62 | &sl_data_locator_bufferqueue_source); 63 | initDataFormat((SLuint32) stream_format_.frame_rate, 64 | (SLuint32) stream_format_.num_audio_channels, 65 | &sl_data_format_pcm); 66 | initDataSource(&sl_data_locator_bufferqueue_source, &sl_data_format_pcm, &sl_data_source); 67 | initDataLocatorOutputMix(output_mix_object_itf, &sl_data_locator_output_mix); 68 | initDataSink(&sl_data_locator_output_mix, &sl_data_sink); 69 | 70 | // Now we have a data source and sink we are able to create the OpenSL Player 71 | createPlayer(engine_itf, &sl_data_source, &sl_data_sink, &sl_player_object_itf_); 72 | realizePlayer(sl_player_object_itf_); 73 | 74 | // If the API level is 24+ we can obtain the newer Android configuration interface which 75 | // allows us to obtain the Java AudioTrack object associated with playback, this can be used 76 | // to query the number of underruns which have occurred on the stream 77 | if (api_level >= JAVA_PROXY_AVAILABLE_FROM_API_LEVEL) { 78 | getAndroidConfigurationInterfaceAPI24(sl_player_object_itf_, &sl_android_config_itf_api24_); 79 | acquireJavaProxy(sl_android_config_itf_api24_, &java_proxy_); 80 | } else { 81 | // On API <24 we don't do anything with the Android configuration interface, however, 82 | // it is left here to demonstrate how it can be obtained 83 | getAndroidConfigurationInterface(sl_player_object_itf_, &sl_android_config_itf_); 84 | } 85 | 86 | getPlayInterface(sl_player_object_itf_, &sl_play_itf_); 87 | getBufferQueueInterface(sl_player_object_itf_, &sl_buffer_queue_itf_); 88 | registerCallback(sl_buffer_queue_itf_, SLPlayerCallback, this); 89 | } 90 | 91 | AudioPlayer::~AudioPlayer() { 92 | if (sl_player_object_itf_ != nullptr){ 93 | (*sl_player_object_itf_)->Destroy(sl_player_object_itf_); 94 | sl_player_object_itf_ = nullptr; 95 | } 96 | delete[] audio_buffer_; 97 | } 98 | 99 | void AudioPlayer::initAudioBuffer(int frames_per_buffer, 100 | int num_audio_channels, 101 | int16_t *&audio_buffer) { 102 | 103 | int samples_per_buffer = frames_per_buffer * num_audio_channels; 104 | audio_buffer = new int16_t[samples_per_buffer]; 105 | memset(audio_buffer, 0, samples_per_buffer * sizeof(int16_t)); 106 | LOGV("audio buffer array allocated %d samples", samples_per_buffer); 107 | } 108 | 109 | void AudioPlayer::initDataLocatorBufferQueue(SLuint32 num_buffers, 110 | SLDataLocator_AndroidSimpleBufferQueue *data_locator) { 111 | 112 | data_locator->locatorType = SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE; 113 | data_locator->numBuffers = num_buffers; 114 | } 115 | 116 | void AudioPlayer::initDataFormat(SLuint32 frame_rate, 117 | SLuint32 num_channels, 118 | SLDataFormat_PCM *data_format) { 119 | 120 | data_format->formatType = SL_DATAFORMAT_PCM; 121 | data_format->numChannels = num_channels; 122 | 123 | // Note: samplesPerSec is an inaccurate name for this property since the expected 124 | // value is the "sample rate in milliHz" 125 | data_format->samplesPerSec = frame_rate * MILLIHERTZ_IN_HERTZ; 126 | data_format->bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16; 127 | data_format->containerSize = SL_PCMSAMPLEFORMAT_FIXED_16; 128 | 129 | // Note: because of an Android bug (id: 35749641) attempting to use indexed channel 130 | // masks results in a non-fast mixer thread. Uncomment this line when bug fixed. 131 | // data_format->channelMask = SL_ANDROID_MAKE_INDEXED_CHANNEL_MASK((1 << num_channels) - 1); 132 | data_format->channelMask = (SLuint32) (1 << num_channels) - 1; 133 | data_format->endianness = SL_BYTEORDER_LITTLEENDIAN; 134 | } 135 | 136 | void AudioPlayer::initDataSource(SLDataLocator_AndroidSimpleBufferQueue *data_locator, 137 | SLDataFormat_PCM *data_format, 138 | SLDataSource *data_source) { 139 | 140 | data_source->pLocator = data_locator; 141 | data_source->pFormat = data_format; 142 | } 143 | 144 | void AudioPlayer::initDataLocatorOutputMix(SLObjectItf output_mix_itf, 145 | SLDataLocator_OutputMix *data_locator) { 146 | 147 | data_locator->locatorType = SL_DATALOCATOR_OUTPUTMIX; 148 | data_locator->outputMix = output_mix_itf; 149 | } 150 | 151 | void AudioPlayer::initDataSink(SLDataLocator_OutputMix *data_locator, SLDataSink *data_sink) { 152 | 153 | data_sink->pLocator = data_locator; 154 | data_sink->pFormat = NULL; 155 | } 156 | 157 | void AudioPlayer::createPlayer(SLEngineItf engine_itf, 158 | SLDataSource *data_source, 159 | SLDataSink *data_sink, 160 | SLObjectItf *player_object_itf) { 161 | 162 | // Note: Adding other output interfaces here may result in your audio being routed using the 163 | // normal path NOT the fast path 164 | const int numInterfaces = 2; 165 | const SLInterfaceID interfaceIds[numInterfaces] = {SL_IID_ANDROIDSIMPLEBUFFERQUEUE, 166 | SL_IID_ANDROIDCONFIGURATION}; 167 | const SLboolean interfacesRequired[numInterfaces] = {SL_BOOLEAN_TRUE, 168 | SL_BOOLEAN_TRUE}; 169 | 170 | SLresult result = (*engine_itf)->CreateAudioPlayer( 171 | engine_itf, 172 | player_object_itf, 173 | data_source, 174 | data_sink, 175 | numInterfaces, 176 | interfaceIds, 177 | interfacesRequired 178 | ); 179 | assert(SL_RESULT_SUCCESS == result); 180 | } 181 | 182 | void AudioPlayer::getAndroidConfigurationInterface(SLObjectItf player_object_itf, 183 | SLAndroidConfigurationItf *config_itf) { 184 | 185 | SLresult result = (*player_object_itf)->GetInterface(player_object_itf, 186 | SL_IID_ANDROIDCONFIGURATION, 187 | config_itf); 188 | assert(SL_RESULT_SUCCESS == result); 189 | } 190 | 191 | void AudioPlayer::getAndroidConfigurationInterfaceAPI24(SLObjectItf player_object_itf, 192 | SLAndroidConfigurationItfAPI24 *config_itf) { 193 | 194 | SLresult result = (*player_object_itf)->GetInterface(player_object_itf, 195 | SL_IID_ANDROIDCONFIGURATION, 196 | config_itf); 197 | assert(SL_RESULT_SUCCESS == result); 198 | } 199 | 200 | void AudioPlayer::realizePlayer(SLObjectItf player_object_itf) { 201 | 202 | SLresult result = (*player_object_itf)->Realize(player_object_itf, 203 | SL_BOOLEAN_FALSE /* async */); 204 | assert(SL_RESULT_SUCCESS == result); 205 | } 206 | 207 | void AudioPlayer::getPlayInterface(SLObjectItf player_object_itf, SLPlayItf *play_itf) { 208 | 209 | SLresult result = (*player_object_itf)->GetInterface(player_object_itf, SL_IID_PLAY, play_itf); 210 | assert(SL_RESULT_SUCCESS == result); 211 | } 212 | 213 | void AudioPlayer::getBufferQueueInterface(SLObjectItf player_object_itf, 214 | SLAndroidSimpleBufferQueueItf *buffer_queue_itf) { 215 | 216 | SLresult result = (*player_object_itf)->GetInterface(player_object_itf, 217 | SL_IID_ANDROIDSIMPLEBUFFERQUEUE, 218 | buffer_queue_itf); 219 | assert(SL_RESULT_SUCCESS == result); 220 | } 221 | 222 | void AudioPlayer::registerCallback(SLAndroidSimpleBufferQueueItf buffer_queue_itf, 223 | sl_player_callback_function callback_function, 224 | void *context) { 225 | 226 | SLresult result = (*buffer_queue_itf)->RegisterCallback(buffer_queue_itf, 227 | callback_function, 228 | context); 229 | assert(SL_RESULT_SUCCESS == result); 230 | } 231 | 232 | void AudioPlayer::play() { 233 | 234 | if (sl_play_itf_ == nullptr) { 235 | LOGE("SLPlayItf was null"); 236 | } else if (renderer_ == nullptr) { 237 | LOGE("Renderer was null"); 238 | } else if (audio_buffer_ == nullptr) { 239 | LOGE("Audio buffer is null"); 240 | } else { 241 | 242 | // set the player's state to playing 243 | SLresult result = (*sl_play_itf_)->SetPlayState(sl_play_itf_, SL_PLAYSTATE_PLAYING); 244 | assert(SL_RESULT_SUCCESS == result); 245 | LOGV("play state set to playing"); 246 | 247 | (void) result; 248 | 249 | // Enqueue buffers of audio data to kick off the callbacks 250 | for (int i = 0; i < stream_format_.num_buffers; i++) { 251 | int samples_rendered = renderer_->render( 252 | stream_format_.frames_per_buffer * stream_format_.num_audio_channels, 253 | audio_buffer_); 254 | LOGV("Enqueuing buffer %d, samples rendered %d ", i, samples_rendered); 255 | 256 | result = (*sl_buffer_queue_itf_)->Enqueue( 257 | sl_buffer_queue_itf_, 258 | audio_buffer_, 259 | samples_rendered * sizeof(audio_buffer_[0])); 260 | assert(SL_RESULT_SUCCESS == result); 261 | } 262 | } 263 | } 264 | 265 | void AudioPlayer::stop() { 266 | 267 | if (sl_play_itf_ == nullptr) { 268 | LOGE("SLPlayItf was null"); 269 | } else { 270 | SLresult result = (*sl_play_itf_)->SetPlayState(sl_play_itf_, SL_PLAYSTATE_STOPPED); 271 | assert(SL_RESULT_SUCCESS == result); 272 | LOGV("play state set to stopped"); 273 | } 274 | } 275 | 276 | void AudioPlayer::processSLCallback(SLAndroidSimpleBufferQueueItf buffer_queue_itf) { 277 | 278 | if (callback_cpu_ids_.size() > 0 && !is_thread_affinity_set_) setThreadAffinity(); 279 | 280 | int num_requested_samples = stream_format_.frames_per_buffer * 281 | stream_format_.num_audio_channels; 282 | int num_rendered_samples = renderer_->render(num_requested_samples, audio_buffer_); 283 | SLresult result = (*buffer_queue_itf)->Enqueue(buffer_queue_itf, 284 | audio_buffer_, 285 | num_rendered_samples * sizeof(int16_t)); 286 | assert(SL_RESULT_SUCCESS == result); 287 | } 288 | 289 | void AudioPlayer::setThreadAffinity() { 290 | 291 | pid_t current_thread_id = gettid(); 292 | cpu_set_t cpu_set; 293 | CPU_ZERO(&cpu_set); 294 | 295 | // If the callback cpu ids aren't specified then bind to the current cpu 296 | if (callback_cpu_ids_.empty()) { 297 | int current_cpu_id = sched_getcpu(); 298 | LOGV("Current CPU ID is %d", current_cpu_id); 299 | CPU_SET(current_cpu_id, &cpu_set); 300 | } else { 301 | 302 | for (size_t i = 0; i < callback_cpu_ids_.size(); i++) { 303 | int cpu_id = callback_cpu_ids_.at(i); 304 | LOGV("CPU ID %d added to cores set", cpu_id); 305 | CPU_SET(cpu_id, &cpu_set); 306 | } 307 | } 308 | 309 | int result = sched_setaffinity(current_thread_id, sizeof(cpu_set_t), &cpu_set); 310 | if (result == 0) { 311 | LOGV("Thread affinity set"); 312 | } else { 313 | LOGW("Error setting thread affinity. Error no: %d", result); 314 | } 315 | 316 | is_thread_affinity_set_ = true; 317 | } 318 | 319 | void AudioPlayer::setCallbackThreadCPUIds(std::vector cpu_ids) { 320 | 321 | is_thread_affinity_set_ = false; 322 | callback_cpu_ids_ = cpu_ids; 323 | } 324 | 325 | void AudioPlayer::acquireJavaProxy(SLAndroidConfigurationItfAPI24 config_itf, jobject *java_proxy) { 326 | 327 | SLresult result = (*config_itf)->AcquireJavaProxy(config_itf, SL_ANDROID_JAVA_PROXY_ROUTING, 328 | java_proxy); 329 | assert(SL_RESULT_SUCCESS == result); 330 | (void) result; 331 | } 332 | 333 | jobject AudioPlayer::getAudioTrack() { 334 | return java_proxy_; 335 | } 336 | -------------------------------------------------------------------------------- /SimpleSynth/app/src/main/cpp/audio_player.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef SIMPLESYNTH_AUDIO_PLAYER_H 18 | #define SIMPLESYNTH_AUDIO_PLAYER_H 19 | 20 | #include 21 | 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include "audio_renderer.h" 27 | #include "audio_common.h" 28 | #include "OpenSLES_Android_API24.h" 29 | 30 | 31 | typedef void (*sl_player_callback_function)(SLAndroidSimpleBufferQueueItf buffer_queue_itf, 32 | void *context); 33 | 34 | class AudioPlayer { 35 | 36 | public: 37 | AudioPlayer(SLEngineItf sl_engine_itf, 38 | SLObjectItf output_mix_itf, 39 | AudioRenderer *renderer, 40 | AudioStreamFormat stream_format, 41 | int api_level); 42 | 43 | virtual ~AudioPlayer(); 44 | 45 | void processSLCallback(SLAndroidSimpleBufferQueueItf buffer_queue_itf); 46 | 47 | void play(); 48 | 49 | void stop(); 50 | 51 | void setCallbackThreadCPUIds(std::vector core_ids); 52 | 53 | jobject getAudioTrack(); 54 | 55 | private: 56 | 57 | // Methods 58 | void initAudioBuffer(int frames_per_buffer, 59 | int num_audio_channels, 60 | int16_t *&audio_buffer); 61 | 62 | void initDataLocatorBufferQueue(SLuint32 num_buffers, 63 | SLDataLocator_AndroidSimpleBufferQueue *data_locator); 64 | 65 | void initDataFormat(SLuint32 frame_rate, 66 | SLuint32 num_channels, 67 | SLDataFormat_PCM *data_format); 68 | 69 | void initDataSource(SLDataLocator_AndroidSimpleBufferQueue *data_locator, 70 | SLDataFormat_PCM *data_format, 71 | SLDataSource *data_source); 72 | 73 | void initDataLocatorOutputMix(SLObjectItf output_mix_itf, 74 | SLDataLocator_OutputMix *data_locator); 75 | 76 | void initDataSink(SLDataLocator_OutputMix *data_locator, 77 | SLDataSink *data_sink); 78 | 79 | void createPlayer(SLEngineItf engine_itf, 80 | SLDataSource *data_source, 81 | SLDataSink *data_sink, 82 | SLObjectItf *player_object_itf); 83 | 84 | void getAndroidConfigurationInterface(SLObjectItf player_object_itf, 85 | SLAndroidConfigurationItf *config_itf); 86 | 87 | void getAndroidConfigurationInterfaceAPI24(SLObjectItf player_object_itf, 88 | SLAndroidConfigurationItfAPI24 *config_itf); 89 | 90 | void realizePlayer(SLObjectItf player_object_itf); 91 | 92 | void getPlayInterface(SLObjectItf player_object_itf, SLPlayItf *play_itf); 93 | 94 | void getBufferQueueInterface(SLObjectItf player_object_itf, 95 | SLAndroidSimpleBufferQueueItf *buffer_queue_itf); 96 | 97 | void registerCallback(SLAndroidSimpleBufferQueueItf buffer_queue_itf, 98 | sl_player_callback_function callback_function, 99 | void *context); 100 | 101 | void setThreadAffinity(); 102 | 103 | void acquireJavaProxy(SLAndroidConfigurationItfAPI24 config_itf, jobject *java_proxy); 104 | 105 | // Member variables 106 | AudioRenderer *renderer_ = nullptr; 107 | AudioStreamFormat stream_format_; 108 | int16_t *audio_buffer_; 109 | jobject java_proxy_ = nullptr; 110 | 111 | // OpenSL objects 112 | SLObjectItf sl_player_object_itf_ = nullptr; 113 | SLAndroidConfigurationItf sl_android_config_itf_ = nullptr; 114 | SLAndroidConfigurationItfAPI24 sl_android_config_itf_api24_ = nullptr; 115 | SLPlayItf sl_play_itf_ = nullptr; 116 | SLAndroidSimpleBufferQueueItf sl_buffer_queue_itf_ = nullptr; 117 | 118 | // Performance options 119 | bool is_thread_affinity_set_ = false; 120 | std::vector callback_cpu_ids_; 121 | }; 122 | 123 | 124 | #endif //SIMPLESYNTH_AUDIO_PLAYER_H 125 | -------------------------------------------------------------------------------- /SimpleSynth/app/src/main/cpp/audio_renderer.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef SIMPLESYNTH_AUDIO_RENDERER_H 18 | #define SIMPLESYNTH_AUDIO_RENDERER_H 19 | 20 | #include 21 | 22 | class AudioRenderer { 23 | 24 | public: 25 | /** 26 | * Render signed 16-bit audio samples into the supplied audio buffer 27 | * 28 | * @param num_samples number of samples to render 29 | * @param audio_buffer array into which samples should be rendered 30 | * @return number of samples which were actually rendered 31 | */ 32 | virtual int render(int num_samples, int16_t *audio_buffer) = 0; 33 | }; 34 | 35 | 36 | #endif //SIMPLESYNTH_AUDIO_RENDERER_H 37 | -------------------------------------------------------------------------------- /SimpleSynth/app/src/main/cpp/cpu_relax.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef SIMPLESYNTH_CPU_RELAX_H 18 | #define SIMPLESYNTH_CPU_RELAX_H 19 | 20 | 21 | /** 22 | * cpu_relax is an architecture specific method of telling the CPU that you don't want it to 23 | * do much work. asm volatile keeps the compiler from optimising these instructions out. 24 | */ 25 | #if defined(__i386__) || defined(__x86_64__) 26 | #define cpu_relax() asm volatile("rep; nop" ::: "memory"); 27 | 28 | #elif defined(__arm__) || defined(__mips__) 29 | #define cpu_relax() asm volatile("":::"memory") 30 | 31 | #elif defined(__aarch64__) 32 | #define cpu_relax() asm volatile("yield" ::: "memory") 33 | 34 | #else 35 | #error "cpu_relax is not defined for this architecture" 36 | #endif 37 | 38 | 39 | #endif //SIMPLESYNTH_CPU_RELAX_H 40 | -------------------------------------------------------------------------------- /SimpleSynth/app/src/main/cpp/jni_bridge.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | #include 19 | #include 20 | #include "audio_player.h" 21 | #include "synthesizer.h" 22 | #include "load_stabilizer.h" 23 | #include "android_log.h" 24 | 25 | // OpenSL ES interfaces 26 | static SLObjectItf sl_engine_object_itf = nullptr; 27 | static SLEngineItf sl_engine_engine_itf = nullptr; 28 | static SLObjectItf sl_output_mix_object_itf = nullptr; 29 | 30 | static LoadStabilizer *load_stabilizer; 31 | static Synthesizer *synth; 32 | static AudioPlayer *player; 33 | static int api_level; 34 | 35 | #define NUM_AUDIO_CHANNELS 2 // 1 = mono, 2 = stereo 36 | 37 | extern "C" { 38 | 39 | // create the engine and output mix objects 40 | JNIEXPORT void JNICALL Java_com_example_simplesynth_MainActivity_native_1createEngine( 41 | JNIEnv *env, 42 | jclass clazz, 43 | jint j_api_level) { 44 | 45 | LOGV("Creating audio engine"); 46 | 47 | api_level = (int) j_api_level; 48 | 49 | // create the OpenSL ES engine and output mix objects 50 | SLresult result; 51 | 52 | result = slCreateEngine(&sl_engine_object_itf, 53 | 0, /* numOptions */ 54 | nullptr, /* pEngineOptions */ 55 | 0, /* numInterfaces */ 56 | nullptr, /* pInterfaceIds */ 57 | nullptr /* pInterfaceRequired */); 58 | SLASSERT(result); 59 | 60 | // realize the engine 61 | result = (*sl_engine_object_itf)->Realize(sl_engine_object_itf, SL_BOOLEAN_FALSE /* async */); 62 | SLASSERT(result); 63 | 64 | // get the engine interface, which is needed to create other objects 65 | result = (*sl_engine_object_itf)->GetInterface(sl_engine_object_itf, 66 | SL_IID_ENGINE, 67 | &sl_engine_engine_itf); 68 | SLASSERT(result); 69 | // create the output mix 70 | result = (*sl_engine_engine_itf)->CreateOutputMix(sl_engine_engine_itf, 71 | &sl_output_mix_object_itf, 72 | 0, 73 | nullptr, 74 | nullptr); 75 | SLASSERT(result); 76 | 77 | // realize the output mix 78 | result = (*sl_output_mix_object_itf)->Realize(sl_output_mix_object_itf, 79 | SL_BOOLEAN_FALSE /* async */); 80 | SLASSERT(result); 81 | } 82 | 83 | JNIEXPORT void JNICALL 84 | Java_com_example_simplesynth_MainActivity_native_1destroyEngine( 85 | JNIEnv *env, 86 | jclass type) { 87 | 88 | if (sl_output_mix_object_itf != nullptr){ 89 | (*sl_output_mix_object_itf)->Destroy(sl_output_mix_object_itf); 90 | sl_output_mix_object_itf = nullptr; 91 | } 92 | if (sl_engine_object_itf != nullptr){ 93 | (*sl_engine_object_itf)->Destroy(sl_engine_object_itf); 94 | sl_engine_object_itf = nullptr; 95 | } 96 | } 97 | 98 | JNIEXPORT jobject JNICALL Java_com_example_simplesynth_MainActivity_native_1createAudioPlayer( 99 | JNIEnv *env, 100 | jclass clazz, 101 | jint j_frame_rate, 102 | jint j_frames_per_buffer, 103 | jint j_num_buffers, 104 | jintArray j_cpu_ids) { 105 | 106 | AudioStreamFormat format; 107 | format.frame_rate = (uint32_t) j_frame_rate; 108 | format.frames_per_buffer = (uint32_t) j_frames_per_buffer; 109 | format.num_audio_channels = NUM_AUDIO_CHANNELS; 110 | format.num_buffers = (uint16_t) j_num_buffers; 111 | 112 | synth = new Synthesizer(format.num_audio_channels, format.frame_rate); 113 | 114 | int64_t callback_period_ns = ((int64_t)format.frames_per_buffer * NANOS_IN_SECOND) / format.frame_rate; 115 | load_stabilizer = new LoadStabilizer(synth, callback_period_ns); 116 | 117 | player = new AudioPlayer(sl_engine_engine_itf, 118 | sl_output_mix_object_itf, 119 | load_stabilizer, 120 | format, 121 | api_level); 122 | 123 | jsize length = env->GetArrayLength(j_cpu_ids); 124 | 125 | if (length > 0){ 126 | // Convert the Java jintArray of CPU IDs into a C++ std::vector 127 | std::vector cpu_ids; 128 | jboolean isCopy; 129 | jint *elements = env->GetIntArrayElements(j_cpu_ids, &isCopy); 130 | for (int i = 0; i < length; i++){ 131 | cpu_ids.push_back(elements[i]); 132 | } 133 | player->setCallbackThreadCPUIds(cpu_ids); 134 | } 135 | 136 | Trace::initialize(); 137 | 138 | player->play(); 139 | return player->getAudioTrack(); 140 | } 141 | 142 | JNIEXPORT void JNICALL 143 | Java_com_example_simplesynth_MainActivity_native_1destroyAudioPlayer( 144 | JNIEnv *env, 145 | jclass type) { 146 | 147 | player->stop(); 148 | delete player; 149 | delete load_stabilizer; 150 | delete synth; 151 | } 152 | 153 | JNIEXPORT void JNICALL Java_com_example_simplesynth_MainActivity_native_1noteOn( 154 | JNIEnv *env, 155 | jclass clazz){ 156 | synth->noteOn(); 157 | } 158 | 159 | JNIEXPORT void JNICALL Java_com_example_simplesynth_MainActivity_native_1noteOff( 160 | JNIEnv *env, 161 | jclass clazz){ 162 | synth->noteOff(); 163 | } 164 | 165 | JNIEXPORT void JNICALL Java_com_example_simplesynth_MainActivity_native_1setWorkCycles( 166 | JNIEnv *env, 167 | jclass clazz, 168 | jint workCycles){ 169 | synth->setWorkCycles((int) workCycles); 170 | } 171 | 172 | JNIEXPORT void JNICALL 173 | Java_com_example_simplesynth_MainActivity_native_1setLoadStabilizationEnabled( 174 | JNIEnv *env, 175 | jclass clazz, 176 | jboolean is_enabled){ 177 | load_stabilizer->setStabilizationEnabled((bool) is_enabled); 178 | } 179 | 180 | } // end extern "C" 181 | -------------------------------------------------------------------------------- /SimpleSynth/app/src/main/cpp/load_stabilizer.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | #include "load_stabilizer.h" 19 | #include "cpu_relax.h" 20 | #include "android_log.h" 21 | #include "audio_common.h" 22 | 23 | #define LOAD_GENERATION_STEP_SIZE_IN_NANOS 1000 24 | #define PERCENTAGE_OF_CALLBACK_TO_USE 0.8 25 | 26 | LoadStabilizer::LoadStabilizer(AudioRenderer *audio_renderer, int64_t callback_period_ns) : 27 | audio_renderer_(audio_renderer), 28 | callback_period_(callback_period_ns), 29 | is_stabilization_enabled_(false), 30 | callback_count_(0){ 31 | 32 | assert(callback_period_ns > 0); 33 | 34 | LOGV("Creating load stabilizer with callback period %lld", (long long)callback_period_); 35 | } 36 | 37 | int LoadStabilizer::render(int num_samples, int16_t *audio_buffer) { 38 | 39 | Trace::beginSection("LoadStabilizer::render start"); 40 | int rendered_samples = 0; 41 | 42 | if (is_stabilization_enabled_){ 43 | 44 | int64_t start_time = get_time(); 45 | if (callback_count_ == 0) callback_epoch_ = start_time; 46 | 47 | // get the deadline for this callback by calculating the periods since the first callback 48 | int64_t time_since_epoch = start_time - callback_epoch_; 49 | int64_t periods_since_epoch = time_since_epoch / callback_period_; 50 | 51 | if (periods_since_epoch < callback_count_){ 52 | 53 | // Previous epoch was set using a late callback 54 | // reset to this new earlier (more accurate) callback time 55 | callback_epoch_ = start_time; 56 | callback_count_ = 0; 57 | time_since_epoch = 0; 58 | periods_since_epoch = 0; 59 | } 60 | 61 | int64_t started_late_duration = time_since_epoch - (periods_since_epoch * callback_period_); 62 | int64_t target_duration = (int64_t)(callback_period_ * 63 | PERCENTAGE_OF_CALLBACK_TO_USE) - started_late_duration; 64 | 65 | Trace::beginSection("Actual load"); 66 | rendered_samples = audio_renderer_->render(num_samples, audio_buffer); 67 | Trace::endSection(); 68 | 69 | int64_t real_execution_duration = get_time() - start_time; 70 | int64_t stabilizing_load_duration = target_duration - real_execution_duration; 71 | 72 | if (stabilizing_load_duration > 0){ 73 | Trace::beginSection("Stabilizing load"); 74 | generateLoad(stabilizing_load_duration); 75 | Trace::endSection(); 76 | } 77 | 78 | callback_count_++; 79 | 80 | } else { 81 | 82 | // just call the wrapped function directly, no load stabilization 83 | Trace::beginSection("Actual load"); 84 | rendered_samples = audio_renderer_->render(num_samples, audio_buffer); 85 | Trace::endSection(); 86 | } 87 | 88 | Trace::endSection(); 89 | 90 | return rendered_samples; 91 | } 92 | 93 | // Generates a stabilizing load by executing cpu instructions for the specified time 94 | void LoadStabilizer::generateLoad(int64_t duration_in_nanos){ 95 | 96 | int64_t current_time = get_time(); 97 | int64_t deadline_time = current_time + duration_in_nanos; 98 | 99 | // ops_per_step gives us an estimated number of operations which need to be run to fully utilize 100 | // the CPU for a fixed amount of time (specified by LOAD_GENERATION_STEP_SIZE_IN_NANOS). 101 | // After each step the ops_per_step value is re-calculated based on the actual time taken to 102 | // execute those operations. 103 | int ops_per_step = (int)(ops_per_nano_ * LOAD_GENERATION_STEP_SIZE_IN_NANOS); 104 | int64_t step_duration = 0; 105 | int64_t previous_time = 0; 106 | 107 | while (current_time <= deadline_time){ 108 | 109 | for (int i = 0; i < ops_per_step; i++){ 110 | cpu_relax(); 111 | } 112 | 113 | previous_time = current_time; 114 | current_time = get_time(); 115 | step_duration = current_time - previous_time; 116 | ops_per_nano_ = ops_per_step / step_duration; 117 | ops_per_step = (int)(ops_per_nano_ * LOAD_GENERATION_STEP_SIZE_IN_NANOS); 118 | } 119 | } 120 | 121 | void LoadStabilizer::setStabilizationEnabled(bool is_enabled){ 122 | LOGV("Load stabilization set to %d", is_enabled); 123 | is_stabilization_enabled_ = is_enabled; 124 | } 125 | -------------------------------------------------------------------------------- /SimpleSynth/app/src/main/cpp/load_stabilizer.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef SIMPLESYNTH_LOAD_STABILIZER_H 18 | #define SIMPLESYNTH_LOAD_STABILIZER_H 19 | 20 | #include 21 | #include "trace.h" 22 | #include "audio_renderer.h" 23 | 24 | class LoadStabilizer : public AudioRenderer { 25 | 26 | public: 27 | LoadStabilizer(AudioRenderer *audio_renderer, int64_t callback_period_ns); 28 | int render(int num_samples, int16_t *audio_buffer); 29 | void generateLoad(int64_t duration_in_nanos); 30 | void setStabilizationEnabled(bool is_enabled); 31 | 32 | private: 33 | AudioRenderer *audio_renderer_; 34 | int64_t callback_period_; 35 | double ops_per_nano_ = 1; 36 | bool is_stabilization_enabled_; 37 | int64_t callback_count_; 38 | int64_t callback_epoch_; 39 | }; 40 | 41 | #endif //SIMPLESYNTH_LOAD_STABILIZER_H 42 | -------------------------------------------------------------------------------- /SimpleSynth/app/src/main/cpp/synthesizer.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | #include "synthesizer.h" 19 | #include "trace.h" 20 | 21 | #define DEFAULT_SINE_WAVE_FREQUENCY 440.0 22 | #define TWO_PI (3.14159 * 2) 23 | 24 | Synthesizer::Synthesizer(int num_audio_channels, int frame_rate): 25 | num_audio_channels_(num_audio_channels), 26 | frame_rate_(frame_rate){ 27 | setWaveFrequency(DEFAULT_SINE_WAVE_FREQUENCY); 28 | } 29 | 30 | int Synthesizer::render(int num_samples, int16_t *audio_buffer) { 31 | 32 | Trace::beginSection("Synthesizer::render"); 33 | 34 | assert(audio_buffer != nullptr); 35 | 36 | // Do some floating point operations to simulate the load required to produce complex 37 | // synthesizer voices 38 | float x = 0; 39 | for (int i = 1; i <= work_cycles_; i++) { 40 | float y = 1 / i; 41 | float z = 2 / i; 42 | x = x / (y * z); 43 | } 44 | 45 | // render an interleaved output with the same sample value per channel 46 | // For example: 6 samples of a 2 channel output stream could look like this 47 | // 1,1,2,2,3,3 48 | 49 | // Only render full frames 50 | int frames = num_samples / num_audio_channels_; 51 | int sample_count = 0; 52 | 53 | for (int i = 0; i < frames; i++){ 54 | 55 | int16_t value = (int16_t) ((is_playing_) ? sin(current_phase_) * current_volume_ : 0); 56 | 57 | for (int j = 0; j < num_audio_channels_; j++){ 58 | audio_buffer[sample_count] = value; 59 | sample_count++; 60 | } 61 | 62 | if (current_phase_ > TWO_PI) current_phase_ -= TWO_PI; 63 | current_phase_ += phase_increment_; 64 | } 65 | 66 | Trace::endSection(); 67 | 68 | return sample_count; 69 | } 70 | 71 | void Synthesizer::setVolume(int volume) { 72 | current_volume_ = (volume < MAXIMUM_AMPLITUDE_VALUE) ? volume : MAXIMUM_AMPLITUDE_VALUE; 73 | } 74 | 75 | void Synthesizer::setWaveFrequency(float wave_frequency) { 76 | phase_increment_ = TWO_PI * wave_frequency / frame_rate_; 77 | } 78 | 79 | void Synthesizer::noteOn() { 80 | is_playing_ = true; 81 | } 82 | 83 | void Synthesizer::noteOff() { 84 | is_playing_ = false; 85 | } 86 | 87 | void Synthesizer::setWorkCycles(int work_cycles){ 88 | work_cycles_ = work_cycles; 89 | } 90 | -------------------------------------------------------------------------------- /SimpleSynth/app/src/main/cpp/synthesizer.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef SIMPLESYNTH_SYNTHESIZER_H 18 | #define SIMPLESYNTH_SYNTHESIZER_H 19 | 20 | #include 21 | #include 22 | #include "audio_renderer.h" 23 | 24 | #define MAXIMUM_AMPLITUDE_VALUE 10000 25 | 26 | 27 | class Synthesizer : public AudioRenderer { 28 | 29 | public: 30 | Synthesizer(int num_audio_channels, int frame_rate); 31 | 32 | virtual int render(int num_samples, int16_t *audio_buffer); 33 | 34 | void setVolume(int volume); 35 | 36 | void setWaveFrequency(float wave_frequency); 37 | 38 | void noteOn(); 39 | 40 | void noteOff(); 41 | 42 | void setWorkCycles(int work_cycles); 43 | 44 | private: 45 | int num_audio_channels_; 46 | int frame_rate_; 47 | double phase_increment_; 48 | double current_phase_ = 0.0; 49 | int current_volume_ = MAXIMUM_AMPLITUDE_VALUE; 50 | bool is_playing_ = false; 51 | int work_cycles_ = 0; 52 | }; 53 | 54 | #endif //SIMPLESYNTH_SYNTHESIZER_H 55 | -------------------------------------------------------------------------------- /SimpleSynth/app/src/main/cpp/trace.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | #include "trace.h" 19 | #include "android_log.h" 20 | 21 | // Tracing functions 22 | static void *(*ATrace_beginSection)(const char *sectionName); 23 | 24 | static void *(*ATrace_endSection)(void); 25 | 26 | typedef void *(*fp_ATrace_beginSection)(const char *sectionName); 27 | 28 | typedef void *(*fp_ATrace_endSection)(void); 29 | 30 | bool Trace::is_tracing_supported_ = false; 31 | 32 | void Trace::beginSection(const char *sectionName) { 33 | 34 | if (is_tracing_supported_) { 35 | ATrace_beginSection(sectionName); 36 | } else { 37 | LOGE("Tracing is either not initialized (call Trace::initialize()) " 38 | "or not supported on this device"); 39 | } 40 | } 41 | 42 | void Trace::endSection() { 43 | 44 | if (is_tracing_supported_) { 45 | ATrace_endSection(); 46 | } 47 | } 48 | 49 | void Trace::initialize() { 50 | 51 | // Using dlsym allows us to use tracing on API 21+ without needing android/trace.h which wasn't 52 | // published until API 23 53 | void *lib = dlopen("libandroid.so", RTLD_NOW | RTLD_LOCAL); 54 | if (lib == nullptr) { 55 | LOGE("Could not open libandroid.so to dynamically load tracing symbols"); 56 | } else { 57 | ATrace_beginSection = 58 | reinterpret_cast( 59 | dlsym(lib, "ATrace_beginSection")); 60 | ATrace_endSection = 61 | reinterpret_cast( 62 | dlsym(lib, "ATrace_endSection")); 63 | 64 | if (ATrace_beginSection != nullptr && ATrace_endSection != nullptr){ 65 | is_tracing_supported_ = true; 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /SimpleSynth/app/src/main/cpp/trace.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef SIMPLESYNTH_TRACE_H 18 | #define SIMPLESYNTH_TRACE_H 19 | 20 | class Trace { 21 | 22 | public: 23 | static void beginSection(const char * sectionName); 24 | static void endSection(); 25 | static void initialize(); 26 | 27 | private: 28 | static bool is_tracing_supported_; 29 | }; 30 | 31 | #endif //SIMPLESYNTH_TRACE_H 32 | -------------------------------------------------------------------------------- /SimpleSynth/app/src/main/java/com/example/simplesynth/MainActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.simplesynth; 18 | 19 | 20 | import android.annotation.TargetApi; 21 | import android.content.Context; 22 | import android.content.SharedPreferences; 23 | import android.content.pm.ActivityInfo; 24 | import android.content.pm.PackageManager; 25 | import android.media.AudioManager; 26 | import android.media.AudioTrack; 27 | import android.os.Build; 28 | import android.os.Bundle; 29 | import android.support.v7.app.AppCompatActivity; 30 | import android.view.WindowManager; 31 | import android.widget.CompoundButton; 32 | import android.widget.SeekBar; 33 | import android.widget.Switch; 34 | import android.widget.TextView; 35 | 36 | import java.util.Timer; 37 | import java.util.TimerTask; 38 | 39 | 40 | public class MainActivity extends AppCompatActivity { 41 | 42 | private static final int NUM_BUFFERS = 2; 43 | private static final int UPDATE_UNDERRUNS_EVERY_MS = 1000; 44 | private static final float VARIABLE_LOAD_LOW_PERCENTAGE = 0.1F; 45 | private static final int VARIABLE_LOAD_LOW_DURATION = 2000; 46 | private static final int VARIABLE_LOAD_HIGH_DURATION = 2000; 47 | public static final int MAXIMUM_WORK_CYCLES = 500000; 48 | private static final int SEEKBAR_STEPS = 100; 49 | private static final float WORK_CYCLES_PER_STEP = MAXIMUM_WORK_CYCLES / SEEKBAR_STEPS; 50 | private static final String PREFERENCES_KEY_WORK_CYCLES = "work_cycles"; 51 | 52 | private static int workCycles = 0; 53 | 54 | static { 55 | System.loadLibrary("SimpleSynth"); 56 | } 57 | 58 | private TextView mDeviceInfoText, mWorkCyclesText; 59 | private AudioTrack mAudioTrack; 60 | private VariableLoadGenerator mLoadThread; 61 | private SharedPreferences mSettings; 62 | private Timer mUnderrunUpdater; 63 | 64 | // Native methods 65 | private static native void native_createEngine(int apiLevel); 66 | private static native void native_destroyEngine(); 67 | private static native AudioTrack native_createAudioPlayer(int frameRate, 68 | int framesPerBuffer, 69 | int numBuffers, 70 | int[] exclusiveCores); 71 | private static native void native_destroyAudioPlayer(); 72 | private static native void native_noteOn(); 73 | private static native void native_noteOff(); 74 | private static native void native_setWorkCycles(int workCycles); 75 | private static native void native_setLoadStabilizationEnabled(boolean isEnabled); 76 | 77 | @Override 78 | protected void onCreate(Bundle savedInstanceState) { 79 | super.onCreate(savedInstanceState); 80 | setContentView(R.layout.activity_main); 81 | 82 | getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 83 | 84 | // Lock to portrait to avoid onCreate being called more than once 85 | setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 86 | 87 | // Load any previously saved values 88 | mSettings = getPreferences(MODE_PRIVATE); 89 | workCycles = mSettings.getInt(PREFERENCES_KEY_WORK_CYCLES, workCycles); 90 | 91 | initDeviceInfoUI(); 92 | initPerformanceConfigurationUI(); 93 | 94 | setSustainedPerformanceMode(); 95 | 96 | // Create a synthesizer whose callbacks are affined to the exclusive core(s) (if available) 97 | int exclusiveCores[] = getExclusiveCores(); 98 | mAudioTrack = createSynth(exclusiveCores); 99 | 100 | // Update the UI when there are underruns 101 | initUnderrunUpdater(); 102 | 103 | setWorkCycles(workCycles); 104 | } 105 | 106 | @Override 107 | protected void onStop(){ 108 | super.onStop(); 109 | SharedPreferences.Editor editor = mSettings.edit(); 110 | editor.putInt(PREFERENCES_KEY_WORK_CYCLES, workCycles); 111 | editor.apply(); 112 | 113 | if (mUnderrunUpdater != null) mUnderrunUpdater.cancel(); 114 | 115 | native_destroyAudioPlayer(); 116 | native_destroyEngine(); 117 | } 118 | 119 | private void initDeviceInfoUI(){ 120 | 121 | mDeviceInfoText = (TextView) findViewById(R.id.deviceInfoText); 122 | 123 | String deviceInfo = ""; 124 | deviceInfo += "API " + Build.VERSION.SDK_INT + "\n"; 125 | deviceInfo += "Build " + Build.ID + " " + 126 | Build.VERSION.CODENAME + " " + 127 | Build.VERSION.RELEASE + " " + 128 | Build.VERSION.INCREMENTAL + "\n"; 129 | 130 | PackageManager pm = getPackageManager(); 131 | boolean claimsLowLatencyFeature = pm.hasSystemFeature(PackageManager.FEATURE_AUDIO_LOW_LATENCY); 132 | deviceInfo += "Hardware flag audio.low_latency: " + claimsLowLatencyFeature + "\n"; 133 | 134 | String claimsProFeature = "Not supported. Only available on API " + 135 | Build.VERSION_CODES.M + "+"; 136 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){ 137 | claimsProFeature = (pm.hasSystemFeature(PackageManager.FEATURE_AUDIO_PRO)) ? 138 | "true" : "false"; 139 | } 140 | deviceInfo += "Hardware flag audio.pro: " + claimsProFeature + "\n"; 141 | 142 | mDeviceInfoText.append(deviceInfo); 143 | } 144 | 145 | private void setSustainedPerformanceMode(){ 146 | 147 | mDeviceInfoText.append("Sustained performance mode: "); 148 | 149 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { 150 | getWindow().setSustainedPerformanceMode(true); 151 | mDeviceInfoText.append("On"); 152 | } else { 153 | mDeviceInfoText.append("Not supported. Only available on API " + 154 | Build.VERSION_CODES.N + "+"); 155 | } 156 | mDeviceInfoText.append("\n"); 157 | } 158 | 159 | // Obtain CPU cores which are reserved for the foreground app 160 | private int[] getExclusiveCores(){ 161 | int exclusiveCores[] = {}; 162 | 163 | mDeviceInfoText.append("Exclusive core ids: "); 164 | 165 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { 166 | mDeviceInfoText.append("Not supported. Only available on API " + 167 | Build.VERSION_CODES.N + "+"); 168 | } else { 169 | exclusiveCores = android.os.Process.getExclusiveCores(); 170 | for (int i : exclusiveCores){ 171 | mDeviceInfoText.append(i + " "); 172 | } 173 | } 174 | mDeviceInfoText.append("\n"); 175 | 176 | return exclusiveCores; 177 | } 178 | 179 | private AudioTrack createSynth(int[] exclusiveCores){ 180 | 181 | // Obtain the optimal output sample rate and buffer size 182 | AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE); 183 | String frameRateString = am.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE); 184 | String framesPerBufferString = 185 | am.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER); 186 | int mFrameRate = Integer.parseInt(frameRateString); 187 | int mFramesPerBuffer = Integer.parseInt(framesPerBufferString); 188 | 189 | native_createEngine(Build.VERSION.SDK_INT); 190 | 191 | return native_createAudioPlayer( 192 | mFrameRate, mFramesPerBuffer, NUM_BUFFERS, exclusiveCores); 193 | } 194 | 195 | private void initPerformanceConfigurationUI(){ 196 | 197 | Switch testToneSwitch = (Switch) findViewById(R.id.testToneSwitch); 198 | testToneSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 199 | @Override 200 | public void onCheckedChanged(CompoundButton compoundButton, boolean b) { 201 | if (b){ 202 | native_noteOn(); 203 | } else { 204 | native_noteOff(); 205 | } 206 | } 207 | }); 208 | 209 | Switch variableLoadSwitch = (Switch) findViewById(R.id.variableLoadSwitch); 210 | variableLoadSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 211 | @Override 212 | public void onCheckedChanged(CompoundButton compoundButton, boolean b) { 213 | if (b) { 214 | if (mLoadThread == null){ 215 | mLoadThread = new VariableLoadGenerator(); 216 | } 217 | mLoadThread.start(); 218 | } else { 219 | if (mLoadThread != null){ 220 | mLoadThread.terminate(); 221 | mLoadThread = null; 222 | } 223 | } 224 | 225 | } 226 | }); 227 | 228 | Switch stabilizedLoadSwitch = (Switch) findViewById(R.id.stabilizedLoadSwitch); 229 | stabilizedLoadSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 230 | @Override 231 | public void onCheckedChanged(CompoundButton compoundButton, boolean b) { 232 | native_setLoadStabilizationEnabled(b); 233 | } 234 | }); 235 | 236 | mWorkCyclesText = (TextView) findViewById(R.id.workCyclesText); 237 | 238 | SeekBar workCyclesSeekBar = (SeekBar) findViewById(R.id.workCycles); 239 | workCyclesSeekBar.setProgress((int)(workCycles / WORK_CYCLES_PER_STEP)); 240 | 241 | workCyclesSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { 242 | @Override 243 | public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { 244 | workCycles = (int)(progress * WORK_CYCLES_PER_STEP); 245 | setWorkCycles(workCycles); 246 | } 247 | 248 | @Override 249 | public void onStartTrackingTouch(SeekBar seekBar) { 250 | } 251 | 252 | @Override 253 | public void onStopTrackingTouch(SeekBar seekBar) { 254 | } 255 | }); 256 | } 257 | 258 | private void setWorkCycles(final int workCycles){ 259 | 260 | native_setWorkCycles(workCycles); 261 | 262 | runOnUiThread(new Runnable() { 263 | @Override 264 | public void run() { 265 | mWorkCyclesText.setText("Work cycles " + workCycles); 266 | } 267 | }); 268 | } 269 | 270 | private void initUnderrunUpdater(){ 271 | 272 | final TextView mUnderrunCountText = (TextView) findViewById(R.id.underrunCountText); 273 | 274 | if (mAudioTrack == null){ 275 | mUnderrunCountText.setText("Underruns: Feature not supported on API <"+ 276 | Build.VERSION_CODES.N + 277 | " see README for more"); 278 | } else { 279 | 280 | mUnderrunUpdater = new Timer(); 281 | mUnderrunUpdater.schedule(new TimerTask() { 282 | @Override 283 | @TargetApi(Build.VERSION_CODES.N) 284 | public void run() { 285 | final int underrunCount; 286 | underrunCount = ((AudioTrack) mAudioTrack).getUnderrunCount(); 287 | runOnUiThread(new Runnable() { 288 | @Override 289 | public void run() { 290 | mUnderrunCountText.setText("Underruns: " + underrunCount); 291 | } 292 | }); 293 | } 294 | },0, UPDATE_UNDERRUNS_EVERY_MS); 295 | } 296 | } 297 | 298 | private class VariableLoadGenerator extends Thread { 299 | 300 | private boolean isRunning = false; 301 | 302 | synchronized void terminate(){ 303 | isRunning = false; 304 | } 305 | 306 | @Override 307 | public void run(){ 308 | 309 | isRunning = true; 310 | 311 | try { 312 | while (isRunning) { 313 | 314 | int lowCycles = (int)(MainActivity.workCycles * VARIABLE_LOAD_LOW_PERCENTAGE); 315 | MainActivity.this.setWorkCycles(lowCycles); 316 | Thread.sleep(VARIABLE_LOAD_LOW_DURATION); 317 | MainActivity.this.setWorkCycles(MainActivity.workCycles); 318 | Thread.sleep(VARIABLE_LOAD_HIGH_DURATION); 319 | } 320 | } catch (InterruptedException e){ 321 | e.printStackTrace(); 322 | } 323 | } 324 | } 325 | } 326 | -------------------------------------------------------------------------------- /SimpleSynth/app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 9 | 10 | 11 | 16 | 20 | 25 | 26 | 27 | 28 | 29 | 34 | 35 | 42 | 43 | 49 | 50 | 56 | 57 | 62 | 67 | 68 | 73 | 74 | 75 | -------------------------------------------------------------------------------- /SimpleSynth/app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/googlearchive/android-audio-high-performance/c232c21bf35d3bfea16537b781c526b8abdcc3cf/SimpleSynth/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /SimpleSynth/app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/googlearchive/android-audio-high-performance/c232c21bf35d3bfea16537b781c526b8abdcc3cf/SimpleSynth/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /SimpleSynth/app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/googlearchive/android-audio-high-performance/c232c21bf35d3bfea16537b781c526b8abdcc3cf/SimpleSynth/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /SimpleSynth/app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/googlearchive/android-audio-high-performance/c232c21bf35d3bfea16537b781c526b8abdcc3cf/SimpleSynth/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /SimpleSynth/app/src/main/res/values-w820dp/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 64dp 6 | 7 | -------------------------------------------------------------------------------- /SimpleSynth/app/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16dp 4 | 16dp 5 | 6 | -------------------------------------------------------------------------------- /SimpleSynth/app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | Simple Synth 3 | 4 | -------------------------------------------------------------------------------- /SimpleSynth/app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /SimpleSynth/build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | repositories { 5 | google() 6 | jcenter() 7 | } 8 | dependencies { 9 | classpath 'com.android.tools.build:gradle:3.2.1' 10 | // NOTE: Do not place your application dependencies here; they belong 11 | // in the individual module build.gradle files 12 | } 13 | } 14 | 15 | allprojects { 16 | repositories { 17 | google() 18 | jcenter() 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /SimpleSynth/gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true 19 | -------------------------------------------------------------------------------- /SimpleSynth/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/googlearchive/android-audio-high-performance/c232c21bf35d3bfea16537b781c526b8abdcc3cf/SimpleSynth/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /SimpleSynth/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Dec 03 17:23:59 GMT 2018 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip 7 | -------------------------------------------------------------------------------- /SimpleSynth/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # For Cygwin, ensure paths are in UNIX format before anything is touched. 46 | if $cygwin ; then 47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 48 | fi 49 | 50 | # Attempt to set APP_HOME 51 | # Resolve links: $0 may be a link 52 | PRG="$0" 53 | # Need this for relative symlinks. 54 | while [ -h "$PRG" ] ; do 55 | ls=`ls -ld "$PRG"` 56 | link=`expr "$ls" : '.*-> \(.*\)$'` 57 | if expr "$link" : '/.*' > /dev/null; then 58 | PRG="$link" 59 | else 60 | PRG=`dirname "$PRG"`"/$link" 61 | fi 62 | done 63 | SAVED="`pwd`" 64 | cd "`dirname \"$PRG\"`/" >&- 65 | APP_HOME="`pwd -P`" 66 | cd "$SAVED" >&- 67 | 68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 69 | 70 | # Determine the Java command to use to start the JVM. 71 | if [ -n "$JAVA_HOME" ] ; then 72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 73 | # IBM's JDK on AIX uses strange locations for the executables 74 | JAVACMD="$JAVA_HOME/jre/sh/java" 75 | else 76 | JAVACMD="$JAVA_HOME/bin/java" 77 | fi 78 | if [ ! -x "$JAVACMD" ] ; then 79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 80 | 81 | Please set the JAVA_HOME variable in your environment to match the 82 | location of your Java installation." 83 | fi 84 | else 85 | JAVACMD="java" 86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 87 | 88 | Please set the JAVA_HOME variable in your environment to match the 89 | location of your Java installation." 90 | fi 91 | 92 | # Increase the maximum file descriptors if we can. 93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 94 | MAX_FD_LIMIT=`ulimit -H -n` 95 | if [ $? -eq 0 ] ; then 96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 97 | MAX_FD="$MAX_FD_LIMIT" 98 | fi 99 | ulimit -n $MAX_FD 100 | if [ $? -ne 0 ] ; then 101 | warn "Could not set maximum file descriptor limit: $MAX_FD" 102 | fi 103 | else 104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 105 | fi 106 | fi 107 | 108 | # For Darwin, add options to specify how the application appears in the dock 109 | if $darwin; then 110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 111 | fi 112 | 113 | # For Cygwin, switch paths to Windows format before running java 114 | if $cygwin ; then 115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /SimpleSynth/gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /SimpleSynth/screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/googlearchive/android-audio-high-performance/c232c21bf35d3bfea16537b781c526b8abdcc3cf/SimpleSynth/screenshot.png -------------------------------------------------------------------------------- /SimpleSynth/settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app' 2 | -------------------------------------------------------------------------------- /aaudio/.google/packaging.yaml: -------------------------------------------------------------------------------- 1 | status: PUBLISHED 2 | technologies: [Android, NDK] 3 | categories: [NDK] 4 | languages: [C++] 5 | solutions: [Mobile] 6 | github: googlesamples/android-audio-high-performance 7 | license: apache2 8 | -------------------------------------------------------------------------------- /aaudio/README.md: -------------------------------------------------------------------------------- 1 | AAudio Sample 2 | ============== 3 | These samples demonstrate how to use the AAudio API: 4 | 5 | 1. hello-aaudio: creates an output (playback) stream and plays a 6 | sine wave when you tap the screen 7 | 1. echo: creates input (recording) and output (playback) streams, 8 | then "echos" the recorded audio to the playback stream. 9 | 10 | [Official AAudio documentation](https://developer.android.com/ndk/guides/audio/aaudio/aaudio.html) 11 | 12 | 13 | Pre-requisites 14 | ------------- 15 | * Android Device with recording capability 16 | * [Android O DP3](https://android-developers.googleblog.com/2017/06/android-o-apis-are-final-get-your-apps.html) (Developer's Preivew) API (android-26) and above 17 | * [NDK-r15](https://developer.android.com/ndk/downloads/index.html) or above 18 | * [Android Studio 2.3.0+](https://developer.android.com/studio/index.html) 19 | 20 | Getting Started 21 | --------------- 22 | 1. [Install Android Studio](https://developer.android.com/studio/index.html) 23 | 1. Clone this sample repository 24 | 1. Import the sample project into Android Studio 25 | - File -> New -> Import Project 26 | - Browse to aaudio/build.gradle 27 | - Click "OK" 28 | 1. Click Run -> Run, choose the sample you wish to run 29 | 30 | Screenshots 31 | ----------- 32 | ![hello-aaudio-screenshot](hello-aaudio-screenshot.png) 33 | ![echo-screenshot](echo-screenshot.png) 34 | 35 | 36 | Support 37 | ------- 38 | If you've found an error in these samples, please [file an issue](https://github.com/googlesamples/android-audio-high-performance/issues/new). 39 | 40 | Patches are encouraged, and may be submitted by [forking this project](https://github.com/googlesamples/android-audio-high-performance/fork) and 41 | submitting a pull request through GitHub. Please see [CONTRIBUTING.md](../CONTRIBUTING.md) for more details. 42 | 43 | - [Stack Overflow](http://stackoverflow.com/questions/tagged/android-ndk) 44 | - [Google+ Community](https://plus.google.com/communities/105153134372062985968) 45 | - [Android Tools Feedback](http://tools.android.com/feedback) 46 | 47 | 48 | License 49 | ------- 50 | Copyright 2017 Google, Inc. 51 | 52 | Licensed to the Apache Software Foundation (ASF) under one or more contributor 53 | license agreements. See the NOTICE file distributed with this work for 54 | additional information regarding copyright ownership. The ASF licenses this 55 | file to you under the Apache License, Version 2.0 (the "License"); you may not 56 | use this file except in compliance with the License. You may obtain a copy of 57 | the License at 58 | 59 | http://www.apache.org/licenses/LICENSE-2.0 60 | 61 | Unless required by applicable law or agreed to in writing, software 62 | distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 63 | WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 64 | License for the specific language governing permissions and limitations under 65 | the License. 66 | 67 | Version History 68 | --------------- 69 | 1. 22nd March 2017: Initial release for Android - O DP1. Directly reading & writing to audio streams 70 | 2. 17th May 2017: Updated for Android-O-DP2 release, using AAudio callback interface 71 | 3. 3rd July 2017: Allow different audio devices (e.g. USB headphones) to be selected and handle stream disconnection 72 | -------------------------------------------------------------------------------- /aaudio/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 19 | 20 | 21 | 22 | buildscript { 23 | repositories { 24 | jcenter() 25 | google() 26 | } 27 | dependencies { 28 | classpath 'com.android.tools.build:gradle:3.3.1' 29 | // NOTE: Do not place your application dependencies here; they belong 30 | // in the individual module build.gradle files 31 | } 32 | } 33 | 34 | allprojects { 35 | repositories { 36 | jcenter() 37 | google() 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /aaudio/common/audio_common.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | #include "audio_common.h" 19 | #include 20 | 21 | static const int32_t audioFormatEnum[] = { 22 | AAUDIO_FORMAT_INVALID, 23 | AAUDIO_FORMAT_UNSPECIFIED, 24 | AAUDIO_FORMAT_PCM_I16, 25 | AAUDIO_FORMAT_PCM_FLOAT, 26 | }; 27 | static const int32_t audioFormatCount = sizeof(audioFormatEnum)/ 28 | sizeof(audioFormatEnum[0]); 29 | 30 | static const uint32_t sampleFormatBPP[] = { 31 | 0xffff, 32 | 0xffff, 33 | 16, //I16 34 | 32, //FLOAT 35 | }; 36 | uint16_t SampleFormatToBpp(aaudio_format_t format) { 37 | for (int32_t i = 0; i < audioFormatCount; ++i) { 38 | if (audioFormatEnum[i] == format) 39 | return sampleFormatBPP[i]; 40 | } 41 | return 0xffff; 42 | } 43 | static const char * audioFormatStr[] = { 44 | "AAUDIO_FORMAT_INVALID", // = -1, 45 | "AAUDIO_FORMAT_UNSPECIFIED", // = 0, 46 | "AAUDIO_FORMAT_PCM_I16", 47 | "AAUDIO_FORMAT_PCM_FLOAT", 48 | }; 49 | const char* FormatToString(aaudio_format_t format) { 50 | for (int32_t i = 0; i < audioFormatCount; ++i) { 51 | if (audioFormatEnum[i] == format) 52 | return audioFormatStr[i]; 53 | } 54 | return "UNKNOW_AUDIO_FORMAT"; 55 | } 56 | 57 | void PrintAudioStreamInfo(const AAudioStream * stream) { 58 | #define STREAM_CALL(c) AAudioStream_##c((AAudioStream*)stream) 59 | LOGI("StreamID: %p", stream); 60 | 61 | LOGI("BufferCapacity: %d", STREAM_CALL(getBufferCapacityInFrames)); 62 | LOGI("BufferSize: %d", STREAM_CALL(getBufferSizeInFrames)); 63 | LOGI("FramesPerBurst: %d", STREAM_CALL(getFramesPerBurst)); 64 | LOGI("XRunCount: %d", STREAM_CALL(getXRunCount)); 65 | LOGI("SampleRate: %d", STREAM_CALL(getSampleRate)); 66 | LOGI("SamplesPerFrame: %d", STREAM_CALL(getChannelCount)); 67 | LOGI("DeviceId: %d", STREAM_CALL(getDeviceId)); 68 | LOGI("Format: %s", FormatToString(STREAM_CALL(getFormat))); 69 | LOGI("SharingMode: %s", (STREAM_CALL(getSharingMode)) == AAUDIO_SHARING_MODE_EXCLUSIVE ? 70 | "EXCLUSIVE" : "SHARED"); 71 | 72 | aaudio_performance_mode_t perfMode = STREAM_CALL(getPerformanceMode); 73 | std::string perfModeDescription; 74 | switch (perfMode){ 75 | case AAUDIO_PERFORMANCE_MODE_NONE: 76 | perfModeDescription = "NONE"; 77 | break; 78 | case AAUDIO_PERFORMANCE_MODE_LOW_LATENCY: 79 | perfModeDescription = "LOW_LATENCY"; 80 | break; 81 | case AAUDIO_PERFORMANCE_MODE_POWER_SAVING: 82 | perfModeDescription = "POWER_SAVING"; 83 | break; 84 | default: 85 | perfModeDescription = "UNKNOWN"; 86 | break; 87 | } 88 | LOGI("PerformanceMode: %s", perfModeDescription.c_str()); 89 | 90 | aaudio_direction_t dir = STREAM_CALL(getDirection); 91 | LOGI("Direction: %s", (dir == AAUDIO_DIRECTION_OUTPUT ? "OUTPUT" : "INPUT")); 92 | if (dir == AAUDIO_DIRECTION_OUTPUT) { 93 | LOGI("FramesReadByDevice: %d", (int32_t)STREAM_CALL(getFramesRead)); 94 | LOGI("FramesWriteByApp: %d", (int32_t)STREAM_CALL(getFramesWritten)); 95 | } else { 96 | LOGI("FramesReadByApp: %d", (int32_t)STREAM_CALL(getFramesRead)); 97 | LOGI("FramesWriteByDevice: %d", (int32_t)STREAM_CALL(getFramesWritten)); 98 | } 99 | #undef STREAM_CALL 100 | } 101 | 102 | int64_t timestamp_to_nanoseconds(timespec ts){ 103 | return (ts.tv_sec * (int64_t) NANOS_PER_SECOND) + ts.tv_nsec; 104 | } 105 | 106 | int64_t get_time_nanoseconds(clockid_t clockid){ 107 | timespec ts; 108 | clock_gettime(clockid, &ts); 109 | return timestamp_to_nanoseconds(ts); 110 | } 111 | 112 | void ConvertMonoToStereo(int16_t *buffer, int32_t numFrames) { 113 | for (int i = numFrames - 1; i >= 0; i--) { 114 | buffer[i*2] = buffer[i]; 115 | buffer[(i*2)+1] = buffer[i]; 116 | } 117 | } -------------------------------------------------------------------------------- /aaudio/common/audio_common.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | #ifndef AAUDIO_AUDIO_COMMON_H 19 | #define AAUDIO_AUDIO_COMMON_H 20 | 21 | #include 22 | #include 23 | 24 | // Time constants 25 | #define NANOS_PER_SECOND 1000000000L 26 | #define NANOS_PER_MILLISECOND 1000000L 27 | 28 | constexpr int kMonoChannelCount = 1; 29 | constexpr int kStereoChannelCount = 2; 30 | 31 | uint16_t SampleFormatToBpp(aaudio_format_t format); 32 | /* 33 | * GetSystemTicks(void): return the time in micro sec 34 | */ 35 | __inline__ uint64_t GetSystemTicks(void) { 36 | struct timeval Time; 37 | gettimeofday( &Time, NULL ); 38 | 39 | return (static_cast(1000000) * Time.tv_sec + Time.tv_usec); 40 | } 41 | 42 | /* 43 | * flag to enable file dumping 44 | */ 45 | //#define ENABLE_LOG 1 46 | 47 | void PrintAudioStreamInfo(const AAudioStream * stream); 48 | 49 | int64_t timestamp_to_nanoseconds(timespec ts); 50 | 51 | int64_t get_time_nanoseconds(clockid_t clockid); 52 | 53 | // Note: buffer must be at least double the length of numFrames to accommodate the stereo data 54 | void ConvertMonoToStereo(int16_t *buffer, int32_t numFrames); 55 | 56 | #endif // AAUDIO_AUDIO_COMMON_H 57 | -------------------------------------------------------------------------------- /aaudio/echo-screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/googlearchive/android-audio-high-performance/c232c21bf35d3bfea16537b781c526b8abdcc3cf/aaudio/echo-screenshot.png -------------------------------------------------------------------------------- /aaudio/echo/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 28 5 | 6 | defaultConfig { 7 | applicationId 'com.google.sample.aaudio.echo' 8 | minSdkVersion 26 9 | targetSdkVersion 28 10 | versionCode 1 11 | versionName '1.0' 12 | ndk { 13 | abiFilters 'armeabi-v7a', 'arm64-v8a' 14 | } 15 | externalNativeBuild { 16 | cmake { 17 | arguments '-DANDROID_STL=c++_shared', '-DANDROID_TOOLCHAIN=clang', 18 | '-DANDROID_PLATFORM=android-28' 19 | } 20 | } 21 | } 22 | buildTypes { 23 | release { 24 | minifyEnabled false 25 | proguardFiles getDefaultProguardFile('proguard-android.txt') 26 | } 27 | } 28 | externalNativeBuild { 29 | cmake { 30 | path 'src/main/cpp/CMakeLists.txt' 31 | } 32 | } 33 | } 34 | 35 | dependencies { 36 | implementation 'com.android.support:appcompat-v7:28.0.0' 37 | implementation 'com.android.support.constraint:constraint-layout:1.1.3' 38 | implementation project(':audio-device') 39 | } 40 | -------------------------------------------------------------------------------- /aaudio/echo/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/gfan/dev/android-sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /aaudio/echo/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 16 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /aaudio/echo/src/main/cpp/AudioEffect.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include "AudioEffect.h" 18 | 19 | void AudioEffect::process(int16_t *inputBuffer, int32_t samplesPerFrame, int32_t numFrames) { 20 | 21 | for (int i = 0; i < (numFrames * samplesPerFrame); i++){ 22 | 23 | // DO SOMETHING MORE EXCITING HERE! 24 | inputBuffer[i] = inputBuffer[i]; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /aaudio/echo/src/main/cpp/AudioEffect.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef AAUDIO_EFFECT_PROCESSOR_H 18 | #define AAUDIO_EFFECT_PROCESSOR_H 19 | 20 | 21 | #include 22 | 23 | class AudioEffect { 24 | public: 25 | void process(int16_t *inputBuffer, int32_t samplesPerFrame, int32_t numFrames); 26 | }; 27 | 28 | 29 | #endif //AAUDIO_EFFECT_PROCESSOR_H 30 | -------------------------------------------------------------------------------- /aaudio/echo/src/main/cpp/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright 2017 The Android Open Source Project 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | cmake_minimum_required(VERSION 3.4.1) 17 | 18 | # Debug utilities 19 | set (DEBUG_UTILS_PATH "../../../../../debug-utils") 20 | set (DEBUG_UTILS_SOURCES ${DEBUG_UTILS_PATH}/trace.cpp) 21 | 22 | # Code shared between AAudio samples 23 | set (AAUDIO_COMMON_PATH "../../../../common") 24 | set (AAUDIO_COMMON_SOURCES ${AAUDIO_COMMON_PATH}/audio_common.cpp) 25 | 26 | add_library(echo SHARED 27 | EchoAudioEngine.cpp 28 | jni_bridge.cpp 29 | AudioEffect.cpp 30 | ${DEBUG_UTILS_SOURCES} 31 | ${AAUDIO_COMMON_SOURCES} 32 | ) 33 | 34 | target_include_directories(echo PRIVATE 35 | ${AAUDIO_COMMON_PATH} 36 | ${DEBUG_UTILS_PATH}) 37 | 38 | target_link_libraries(echo android atomic log aaudio) 39 | -------------------------------------------------------------------------------- /aaudio/echo/src/main/cpp/EchoAudioEngine.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef AAUDIO_ECHOAUDIOENGINE_H 18 | #define AAUDIO_ECHOAUDIOENGINE_H 19 | 20 | #include 21 | #include "audio_common.h" 22 | #include "AudioEffect.h" 23 | 24 | class EchoAudioEngine { 25 | 26 | public: 27 | ~EchoAudioEngine(); 28 | void setRecordingDeviceId(int32_t deviceId); 29 | void setPlaybackDeviceId(int32_t deviceId); 30 | void setEchoOn(bool isEchoOn); 31 | aaudio_data_callback_result_t dataCallback(AAudioStream *stream, 32 | void *audioData, 33 | int32_t numFrames); 34 | void errorCallback(AAudioStream *stream, 35 | aaudio_result_t __unused error); 36 | 37 | private: 38 | 39 | bool isEchoOn_ = false; 40 | bool isFirstDataCallback_ = true; 41 | int32_t recordingDeviceId_ = AAUDIO_UNSPECIFIED; 42 | int32_t playbackDeviceId_ = AAUDIO_UNSPECIFIED; 43 | aaudio_format_t format_ = AAUDIO_FORMAT_PCM_I16; 44 | int32_t sampleRate_; 45 | int32_t inputChannelCount_ = kMonoChannelCount; 46 | int32_t outputChannelCount_ = kStereoChannelCount; 47 | AAudioStream *recordingStream_ = nullptr; 48 | AAudioStream *playStream_ = nullptr; 49 | int32_t framesPerBurst_; 50 | std::mutex restartingLock_; 51 | AudioEffect audioEffect_; 52 | 53 | void openRecordingStream(); 54 | void drainRecordingStream(void *audioData, int32_t numFrames); 55 | void openPlaybackStream(); 56 | 57 | void startStream(AAudioStream* stream); 58 | void stopStream(AAudioStream* stream); 59 | void closeStream(AAudioStream* stream); 60 | 61 | void openAllStreams(); 62 | void closeAllStreams(); 63 | void restartStreams(); 64 | AAudioStreamBuilder* createStreamBuilder(); 65 | 66 | void setupCommonStreamParameters(AAudioStreamBuilder *builder); 67 | void setupRecordingStreamParameters(AAudioStreamBuilder *builder); 68 | void setupPlaybackStreamParameters(AAudioStreamBuilder *builder); 69 | void warnIfNotLowLatency(AAudioStream *stream); 70 | 71 | 72 | }; 73 | 74 | #endif //AAUDIO_ECHOAUDIOENGINE_H 75 | -------------------------------------------------------------------------------- /aaudio/echo/src/main/cpp/jni_bridge.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | #include 19 | #include 20 | #include "EchoAudioEngine.h" 21 | 22 | static EchoAudioEngine *engine = nullptr; 23 | 24 | extern "C" { 25 | 26 | JNIEXPORT bool JNICALL 27 | Java_com_google_sample_aaudio_echo_EchoEngine_create(JNIEnv *env, 28 | jclass) { 29 | if (engine == nullptr) { 30 | engine = new EchoAudioEngine(); 31 | } 32 | 33 | return (engine != nullptr); 34 | } 35 | 36 | JNIEXPORT void JNICALL 37 | Java_com_google_sample_aaudio_echo_EchoEngine_delete(JNIEnv *env, 38 | jclass) { 39 | delete engine; 40 | engine = nullptr; 41 | } 42 | 43 | JNIEXPORT void JNICALL 44 | Java_com_google_sample_aaudio_echo_EchoEngine_setEchoOn(JNIEnv *env, 45 | jclass, jboolean isEchoOn) { 46 | if (engine == nullptr) { 47 | LOGE("Engine is null, you must call createEngine before calling this method"); 48 | return; 49 | } 50 | 51 | engine->setEchoOn(isEchoOn); 52 | } 53 | 54 | JNIEXPORT void JNICALL 55 | Java_com_google_sample_aaudio_echo_EchoEngine_setRecordingDeviceId(JNIEnv *env, 56 | jclass, jint deviceId) { 57 | if (engine == nullptr) { 58 | LOGE("Engine is null, you must call createEngine before calling this method"); 59 | return; 60 | } 61 | 62 | engine->setRecordingDeviceId(deviceId); 63 | } 64 | 65 | JNIEXPORT void JNICALL 66 | Java_com_google_sample_aaudio_echo_EchoEngine_setPlaybackDeviceId(JNIEnv *env, 67 | jclass, jint deviceId) { 68 | if (engine == nullptr) { 69 | LOGE("Engine is null, you must call createEngine before calling this method"); 70 | return; 71 | } 72 | 73 | engine->setPlaybackDeviceId(deviceId); 74 | } 75 | 76 | 77 | } 78 | -------------------------------------------------------------------------------- /aaudio/echo/src/main/cpp/ndk-stl-config.cmake: -------------------------------------------------------------------------------- 1 | # Copy shared STL files to Android Studio output directory so they can be 2 | # packaged in the APK. 3 | # Usage: 4 | # 5 | # find_package(ndk-stl REQUIRED) 6 | # 7 | # or 8 | # 9 | # find_package(ndk-stl REQUIRED PATHS ".") 10 | 11 | if(NOT ${ANDROID_STL} MATCHES "_shared") 12 | return() 13 | endif() 14 | 15 | function(configure_shared_stl lib_path so_base) 16 | message("Configuring STL ${so_base} for ${ANDROID_ABI}") 17 | configure_file( 18 | "${ANDROID_NDK}/sources/cxx-stl/${lib_path}/libs/${ANDROID_ABI}/lib${so_base}.so" 19 | "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/lib${so_base}.so" 20 | COPYONLY) 21 | endfunction() 22 | 23 | if("${ANDROID_STL}" STREQUAL "libstdc++") 24 | # The default minimal system C++ runtime library. 25 | elseif("${ANDROID_STL}" STREQUAL "gabi++_shared") 26 | # The GAbi++ runtime (shared). 27 | message(FATAL_ERROR "gabi++_shared was not configured by ndk-stl package") 28 | elseif("${ANDROID_STL}" STREQUAL "stlport_shared") 29 | # The STLport runtime (shared). 30 | configure_shared_stl("stlport" "stlport_shared") 31 | elseif("${ANDROID_STL}" STREQUAL "gnustl_shared") 32 | # The GNU STL (shared). 33 | configure_shared_stl("gnu-libstdc++/4.9" "gnustl_shared") 34 | elseif("${ANDROID_STL}" STREQUAL "c++_shared") 35 | # The LLVM libc++ runtime (shared). 36 | configure_shared_stl("llvm-libc++" "c++_shared") 37 | else() 38 | message(FATAL_ERROR "STL configuration ANDROID_STL=${ANDROID_STL} is not supported") 39 | endif() 40 | 41 | -------------------------------------------------------------------------------- /aaudio/echo/src/main/java/com/google/sample/aaudio/echo/EchoEngine.java: -------------------------------------------------------------------------------- 1 | package com.google.sample.aaudio.echo; 2 | /* 3 | * Copyright 2017 The Android Open Source Project 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | import android.content.Context; 19 | import android.media.AudioFormat; 20 | import android.media.AudioManager; 21 | import android.media.AudioRecord; 22 | import android.util.Log; 23 | 24 | public enum EchoEngine { 25 | 26 | INSTANCE; 27 | 28 | // Load native library 29 | static { 30 | System.loadLibrary("echo"); 31 | } 32 | 33 | // Native methods 34 | static native boolean create(); 35 | static native void delete(); 36 | static native void setEchoOn(boolean isEchoOn); 37 | static native void setRecordingDeviceId(int deviceId); 38 | static native void setPlaybackDeviceId(int deviceId); 39 | } 40 | -------------------------------------------------------------------------------- /aaudio/echo/src/main/java/com/google/sample/aaudio/echo/MainActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.sample.aaudio.echo; 18 | 19 | import android.Manifest; 20 | import android.app.Activity; 21 | import android.content.pm.PackageManager; 22 | import android.media.AudioManager; 23 | import android.os.Bundle; 24 | import android.support.annotation.NonNull; 25 | import android.support.v4.app.ActivityCompat; 26 | import android.util.Log; 27 | import android.view.View; 28 | import android.widget.AdapterView; 29 | import android.widget.Button; 30 | import android.widget.TextView; 31 | import android.widget.Toast; 32 | 33 | import com.google.sample.audio_device.AudioDeviceListEntry; 34 | import com.google.sample.audio_device.AudioDeviceSpinner; 35 | 36 | /** 37 | * TODO: Update README.md and go through and comment sample 38 | */ 39 | public class MainActivity extends Activity 40 | implements ActivityCompat.OnRequestPermissionsResultCallback { 41 | 42 | private static final String TAG = MainActivity.class.getName(); 43 | private static final int AUDIO_ECHO_REQUEST = 0; 44 | 45 | private TextView statusText; 46 | private Button toggleEchoButton; 47 | private AudioDeviceSpinner recordingDeviceSpinner; 48 | private AudioDeviceSpinner playbackDeviceSpinner; 49 | private boolean isPlaying = false; 50 | 51 | @Override 52 | protected void onCreate(Bundle savedInstanceState) { 53 | super.onCreate(savedInstanceState); 54 | setContentView(R.layout.activity_main); 55 | 56 | statusText = findViewById(R.id.status_view_text); 57 | toggleEchoButton = findViewById(R.id.button_toggle_echo); 58 | toggleEchoButton.setOnClickListener(new View.OnClickListener() { 59 | @Override 60 | public void onClick(View view) { 61 | toggleEcho(); 62 | } 63 | }); 64 | toggleEchoButton.setText(getString(R.string.start_echo)); 65 | 66 | recordingDeviceSpinner = findViewById(R.id.recording_devices_spinner); 67 | recordingDeviceSpinner.setDirectionType(AudioManager.GET_DEVICES_INPUTS); 68 | recordingDeviceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 69 | @Override 70 | public void onItemSelected(AdapterView adapterView, View view, int i, long l) { 71 | EchoEngine.setRecordingDeviceId(getRecordingDeviceId()); 72 | } 73 | 74 | @Override 75 | public void onNothingSelected(AdapterView adapterView) { 76 | // Do nothing 77 | } 78 | }); 79 | 80 | playbackDeviceSpinner = findViewById(R.id.playback_devices_spinner); 81 | playbackDeviceSpinner.setDirectionType(AudioManager.GET_DEVICES_OUTPUTS); 82 | playbackDeviceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 83 | @Override 84 | public void onItemSelected(AdapterView adapterView, View view, int i, long l) { 85 | EchoEngine.setPlaybackDeviceId(getPlaybackDeviceId()); 86 | } 87 | 88 | @Override 89 | public void onNothingSelected(AdapterView adapterView) { 90 | // Do nothing 91 | } 92 | }); 93 | 94 | EchoEngine.create(); 95 | } 96 | 97 | @Override 98 | protected void onStart() { 99 | super.onStart(); 100 | setVolumeControlStream(AudioManager.STREAM_MUSIC); 101 | } 102 | 103 | @Override 104 | protected void onDestroy() { 105 | EchoEngine.delete(); 106 | super.onDestroy(); 107 | } 108 | 109 | public void toggleEcho() { 110 | if (isPlaying) { 111 | stopEchoing(); 112 | } else { 113 | startEchoing(); 114 | } 115 | } 116 | 117 | private void startEchoing() { 118 | Log.d(TAG, "Attempting to start"); 119 | 120 | if (!isRecordPermissionGranted()){ 121 | requestRecordPermission(); 122 | return; 123 | } 124 | 125 | setSpinnersEnabled(false); 126 | EchoEngine.setEchoOn(true); 127 | statusText.setText(R.string.status_echoing); 128 | toggleEchoButton.setText(R.string.stop_echo); 129 | isPlaying = true; 130 | } 131 | 132 | private void stopEchoing() { 133 | Log.d(TAG, "Playing, attempting to stop"); 134 | EchoEngine.setEchoOn(false); 135 | resetStatusView(); 136 | toggleEchoButton.setText(R.string.start_echo); 137 | isPlaying = false; 138 | setSpinnersEnabled(true); 139 | } 140 | 141 | private void setSpinnersEnabled(boolean isEnabled){ 142 | recordingDeviceSpinner.setEnabled(isEnabled); 143 | playbackDeviceSpinner.setEnabled(isEnabled); 144 | } 145 | 146 | private int getRecordingDeviceId(){ 147 | return ((AudioDeviceListEntry)recordingDeviceSpinner.getSelectedItem()).getId(); 148 | } 149 | 150 | private int getPlaybackDeviceId(){ 151 | return ((AudioDeviceListEntry)playbackDeviceSpinner.getSelectedItem()).getId(); 152 | } 153 | 154 | private boolean isRecordPermissionGranted() { 155 | return (ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == 156 | PackageManager.PERMISSION_GRANTED); 157 | } 158 | 159 | private void requestRecordPermission(){ 160 | ActivityCompat.requestPermissions( 161 | this, 162 | new String[]{Manifest.permission.RECORD_AUDIO}, 163 | AUDIO_ECHO_REQUEST); 164 | } 165 | private void resetStatusView() { 166 | statusText.setText(R.string.status_warning); 167 | } 168 | 169 | @Override 170 | public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, 171 | @NonNull int[] grantResults) { 172 | 173 | if (AUDIO_ECHO_REQUEST != requestCode) { 174 | super.onRequestPermissionsResult(requestCode, permissions, grantResults); 175 | return; 176 | } 177 | 178 | if (grantResults.length != 1 || 179 | grantResults[0] != PackageManager.PERMISSION_GRANTED) { 180 | 181 | // User denied the permission, without this we cannot record audio 182 | // Show a toast and update the status accordingly 183 | statusText.setText(R.string.status_record_audio_denied); 184 | Toast.makeText(getApplicationContext(), 185 | getString(R.string.need_record_audio_permission), 186 | Toast.LENGTH_SHORT) 187 | .show(); 188 | } else { 189 | // Permission was granted, start echoing 190 | toggleEcho(); 191 | } 192 | } 193 | } 194 | -------------------------------------------------------------------------------- /aaudio/echo/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 24 | 25 | 26 | 35 | 43 | 52 | 60 |