


Example of recording processing code that implements a speaking function similar to WeChat
package com.example.testaudio; import java.io.File; import android.app.Activity; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.media.MediaRecorder; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.Menu; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.widget.Button; import android.widget.TextView; public class MainActivity extends Activity { private MediaRecorder recoder = null; private MediaPlayer player = null; private String theMediaPath; TextView tv = null; TextView tvRecord = null; Button testBtn = null; Button testBtn2 = null; Button stopBtn = null; Button playBtn = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView)findViewById(R.id.textView1); tvRecord = (TextView)findViewById(R.id.tvRecord); testBtn = (Button)findViewById(R.id.button1); testBtn2 = (Button)findViewById(R.id.button2); stopBtn = (Button)findViewById(R.id.buttonStop); playBtn = (Button)findViewById(R.id.buttonPlay); testBtn2.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { Log.i("testactivity", "setOnTouchListener:"+event.getAction()); switch(event.getAction()) { case MotionEvent.ACTION_UP: { Log.i("testactivity", "停止录音"); stopRecording(); break; } case MotionEvent.ACTION_DOWN: { Log.i("testactivity", "开始录音"); startRecording(); break; } default: break; } return false; } }); testBtn.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { startRecording(); testBtn.setEnabled(false); stopBtn.setEnabled(true); } }); stopBtn.setEnabled(false); stopBtn.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { stopRecording(); testBtn.setEnabled(true); playBtn.setEnabled(true); stopBtn.setEnabled(false); } }); playBtn.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { playRecordFile(theMediaPath); stopBtn.setEnabled(true); } }); } protected void playRecordFile(String _file) { try { File f = new File(_file); if(!f.exists()) { tv.setText("文件不存在:" + _file); return; } } catch(Exception e) { Log.i("testactivity", e.getMessage()); } try { player = new MediaPlayer(); player.setDataSource(_file); player.prepare(); player.setOnCompletionListener(new OnCompletionListener() { public void onCompletion(MediaPlayer arg0) { tv.setText("播放完毕"); stopBtn.setEnabled(false); } }); player.start(); } catch(Exception e) { Log.e("testactivity", "play failed:" + e.getMessage()); } } /** * 停止录音处理 */ protected void stopRecording() { if(recoder != null) { Log.i("testactivity", "停止录音"); recoder.stop(); recoder.release(); recoder = null; endtime = System.currentTimeMillis(); _handleRecordComplete(); } if(player != null) { Log.i("testactivity", "停止播放"); player.stop(); player.release(); player = null; } } /** * 开始录音处理 */ protected void startRecording() { theMediaPath = Environment.getExternalStorageDirectory().getAbsolutePath(); theMediaPath += "/audiotest.3gp"; recoder = new MediaRecorder(); recoder.setAudioSource(MediaRecorder.AudioSource.MIC); recoder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); recoder.setOutputFile(theMediaPath); recoder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); starttime = System.currentTimeMillis(); updateMicStatus(); try { recoder.prepare(); recoder.start(); _handleRecordStart(); } catch (Exception e) { Log.e("testactivity", "prepared failed:" + e.getMessage()); _handleRecordStartError(e); } } //定时器 private static long maxtime = 30*1000; //30秒 private long starttime = 0l; private long endtime = 0l; private final Handler mHandler = new Handler(); private Runnable mUpdateMicStatusTimer = new Runnable() { public void run() { //判断是否超时 if(starttime > 0 && System.currentTimeMillis() - starttime > maxtime) { Log.e("testactivity", "超时的录音时间,直接停止"); stopRecording(); return; } //更新分贝状态 updateMicStatus(); } }; /** * 更新话筒状态 分贝是也就是相对响度 分贝的计算公式K=20lg(Vo/Vi) Vo当前振幅值 Vi基准值为600:我是怎么制定基准值的呢? 当20 * * Math.log10(mMediaRecorder.getMaxAmplitude() / Vi)==0的时候vi就是我所需要的基准值 * 当我不对着麦克风说任何话的时候,测试获得的mMediaRecorder.getMaxAmplitude()值即为基准值。 * Log.i("mic_", "麦克风的基准值:" + mMediaRecorder.getMaxAmplitude());前提时不对麦克风说任何话 */ private int BASE = 600; private int SPACE = 300;// 间隔取样时间 private void updateMicStatus() { if (recoder != null) { // int vuSize = 10 * mMediaRecorder.getMaxAmplitude() / 32768; int ratio = recoder.getMaxAmplitude() / BASE; int db = 0;// 分贝 if (ratio > 1) db = (int) (20 * Math.log10(ratio)); _handleRecordVoice(db); mHandler.postDelayed(mUpdateMicStatusTimer, SPACE); /* * if (db > 1) { vuSize = (int) (20 * Math.log10(db)); Log.i("mic_", * "麦克风的音量的大小:" + vuSize); } else Log.i("mic_", "麦克风的音量的大小:" + 0); */ } } private void _handleRecordStart() { //开始录音的接收函数 tv.setText("开始录音..."); //starttime 开始时间 } private void _handleRecordStartError(Exception e) { //开始录音的接收函数失败 tv.setText("开始录音失败:" + e.getMessage()); } private void _handleRecordComplete() { //结束录音 tv.setText("停止录音:" + theMediaPath); } private void _handleRecordVoice(int _db) { //声音事件侦听,转换成分贝 tvRecord.setText(""+_db); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
The above is the detailed content of Example of recording processing code that implements a speaking function similar to WeChat. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

H5 is more flexible and customizable, but requires skilled technology; mini programs are quick to get started and easy to maintain, but are limited by the WeChat framework.

This article provides a detailed guide to safe download of Ouyi OKX App in China. Due to restrictions on domestic app stores, users are advised to download the App through the official website of Ouyi OKX, or use the QR code provided by the official website to scan and download. During the download process, be sure to verify the official website address, check the application permissions, perform a security scan after installation, and enable two-factor verification. During use, please abide by local laws and regulations, use a safe network environment, protect account security, be vigilant against fraud, and invest rationally. This article is for reference only and does not constitute investment advice. Digital asset transactions are at your own risk.

H5. The main difference between mini programs and APP is: technical architecture: H5 is based on web technology, and mini programs and APP are independent applications. Experience and functions: H5 is light and easy to use, with limited functions; mini programs are lightweight and have good interactiveness; APPs are powerful and have smooth experience. Compatibility: H5 is cross-platform compatible, applets and APPs are restricted by the platform. Development cost: H5 has low development cost, medium mini programs, and highest APP. Applicable scenarios: H5 is suitable for information display, applets are suitable for lightweight applications, and APPs are suitable for complex functions.

Discussion on the JS resource caching issue of Enterprise WeChat. When upgrading project functions, some users often encounter situations where they fail to successfully upgrade, especially in the enterprise...

Compatibility issues and troubleshooting methods for company security software and application. Many companies will install security software in order to ensure intranet security. However, security software sometimes...

The choice of H5 and applet depends on the requirements. For applications with cross-platform, rapid development and high scalability, choose H5; for applications with native experience, rich functions and platform dependencies, choose applets.

H5 development tools recommendations: VSCode, WebStorm, Atom, Brackets, Sublime Text; Mini Program Development Tools: WeChat Developer Tools, Alipay Mini Program Developer Tools, Baidu Smart Mini Program IDE, Toutiao Mini Program Developer Tools, Taro.
