牙叔教程 简单易懂
效果
环境
手机: Mi 11 Pro
Android版本: 12
Autojs版本: 9.1.6
源码
"ui"; /* * @version: 1.0 * @Date: 2022-02-23 17:34:13 * @LastEditTime: 2022-02-23 18:35:14 * @LastEditors: 牙叔 * @Description: * @FilePath: \autojs获取音量分贝\main.js * @名人名言: 牙叔教程 简单易懂 * @bilibili: 牙叔教程 * @公众号: 牙叔教程 * @QQ群: 747748653 */ engines.all().map((ScriptEngine) => { if (engines.myEngine().toString() !== ScriptEngine.toString()) { ScriptEngine.forceStop(); } }); importClass(android.media.AudioFormat); importClass(android.media.AudioRecord); importClass(android.media.MediaRecorder); importClass(android.util.Log); importClass(android.content.pm.PackageManager); ui.layout( <vertical> <text text="噪音测试" margin="10" textSize="60sp" gravity="center" textStyle="bold"></text> <text id="author" textSize="22sp" marginBottom="6" textColor="#fbfbfe" bg="#00afff" w="*" gravity="center"> 牙叔教程 </text> <horizontal w="*" gravity="center"> <text id="value" w="0" layout_weight="3" text="Hello World" textSize="39sp" gravity="center" /> <text text="db" w="0" layout_weight="1" textSize="39sp" gravity="left" /> </horizontal> </vertical> ); if (checkPermission("android.permission.RECORD_AUDIO")) { log("有录音权限"); main(); } else { log("没有录音权限"); runtime.requestPermissions(["record_audio"]); } /* -------------------------------------------------------------------------- */ function checkPermission(permission) { pm = context.getPackageManager(); return (havePermission = PackageManager.PERMISSION_GRANTED == pm.checkPermission(permission, context.getPackageName().toString())); } function main() { getNoiseLevel(); } function getNoiseLevel() { let SAMPLE_RATE_IN_HZ = 8000; let BUFFER_SIZE = AudioRecord.getMinBufferSize( SAMPLE_RATE_IN_HZ, AudioFormat.CHANNEL_IN_DEFAULT, AudioFormat.ENCODING_PCM_16BIT ); let mAudioRecord; let isGetVoiceRun; if (isGetVoiceRun) { log("还在录着呢"); return; } mAudioRecord = new AudioRecord( MediaRecorder.AudioSource.MIC, SAMPLE_RATE_IN_HZ, AudioFormat.CHANNEL_IN_DEFAULT, AudioFormat.ENCODING_PCM_16BIT, BUFFER_SIZE ); if (mAudioRecord == null) { log("sound", "mAudioRecord初始化失败"); } isGetVoiceRun = true; setTimeout(() => { isGetVoiceRun = false; }, 5000); threads.start(function () { mAudioRecord.startRecording(); let buffer = util.java.array(java.lang.Short.TYPE, BUFFER_SIZE); while (isGetVoiceRun) { //r是实际读取的数据长度,一般而言r会小于buffersize let r = mAudioRecord.read(buffer, 0, BUFFER_SIZE); let v = 0; // 将 buffer 内容取出,进行平方和运算 for (let i = 0; i < buffer.length; i++) { v += buffer[i] * buffer[i]; } // 平方和除以数据总长度,得到音量大小。 let mean = v / r; let volume = 10 * Math.log10(mean); log("分贝值:" + volume); ui.post(() => { ui.value.setText(volume.toFixed(2)); }); // 大概一秒十次 sleep(100); } mAudioRecord.stop(); mAudioRecord.release(); mAudioRecord = null; }); }
参考
相关教程
https://www.yuque.com/go/doc/66524497
名人名言
思路是最重要的, 其他的百度, bing, stackoverflow, github, 安卓文档, autojs文档, 最后才是群里问问
--- 牙叔教程
声明
部分内容来自网络
本教程仅用于学习, 禁止用于其他用途