录音 APK
  HvTJUzsxOBtS 2023年11月25日 28 0


####1、程序功能
打开之后 播放音乐 ,同时通过mic 录音,最后显示录音过程中最大音量和平均音量。

####2、layout 布局

录音 APK_record

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/mic_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="30dp"
        android:layout_marginTop="20dp"
        android:text="Recording" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:gravity="center"
        android:layout_marginTop="50dp"
        android:orientation="vertical">

        <TextView
            android:id="@+id/avg_vol"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="avg :"
            android:textSize="30.0dp" />

        <TextView
            android:id="@+id/max_vol"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="max :"
            android:textSize="30.0dp" />
    </LinearLayout>



</LinearLayout>

####3、AndroidManifest.xml 文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.lumeng.myrecordapplication">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

####4、功能代码实现

package com.example.lumeng.myrecordapplication;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;

public class MainActivity extends AppCompatActivity implements MediaPlayer.OnCompletionListener {
    private static String TAG = "MainActivity";
    private TextView avg_View,max_View;

    private MediaPlayer mPlayer;
    private boolean isPlay = false;

    private Thread mPlayThread;
    private Thread mRecordThread;
    private MediaRecorder mMediaRecorder;
    File soundFile=null;


    private static final int VALUE = 1;
    private int getValueTime = 100;
    private static double dbValueSum = 0;
    private static double getDbValueNum = 0;
    private static double avg_db = 0;
    private static double max_db = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        avg_View = (TextView) findViewById(R.id.avg_vol);
        max_View = (TextView) findViewById(R.id.max_vol);

        //播放歌曲的线程
        mPlayThread = new Thread(new Runnable() {
            @Override
            public void run() {
                startPlay();
            }
        });

        //录音的线程
        mRecordThread = new Thread(new Runnable() {
            @Override
            public void run() {
                startRecord();
            }
        });

        //开始播放,开始录音
        mPlayThread.start();
        mRecordThread.start();

    }


    //开始播放
    private void startPlay() {
        if (isPlay == true) {
            return;
        }
        isPlay = true;
        mPlayer = MediaPlayer.create(getApplicationContext(), R.raw.nlch);
        mPlayer.setOnCompletionListener(this);
        mPlayer.setLooping(false);
        mPlayer.start();
    }


    //结束播放
    private void stopPlay() {
        isPlay = false;
        if (mPlayer != null) {
            mPlayer.stop();
            mPlayer.release();
            mPlayer = null;
        }
    }

    /**
     * startRecord.
     */

    //开始录音
    public void startRecord() {

        if(mMediaRecorder==null) {
            //将录音文件保存内存卡
            File dir = new File(Environment.getExternalStorageDirectory(), "sound");
            if (!dir.exists()) {
                dir.mkdirs();
            }
            Log.v(TAG,"creat recording file ");
            soundFile = new File(dir, System.currentTimeMillis() + ".amr");
            if (!soundFile.exists()) {
                try {
                    soundFile.createNewFile();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            Log.v(TAG,"creat recording ");
            mMediaRecorder = new MediaRecorder();
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_WB);
            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_WB);
            mMediaRecorder.setOutputFile(soundFile.getAbsolutePath());

            try {
                Log.v(TAG,"recording start");
                mMediaRecorder.prepare();
                mMediaRecorder.start();                                                                                                //开始录音
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                mMediaRecorder.reset();
                mMediaRecorder.release();
                mMediaRecorder = null;
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                mMediaRecorder.reset();
                mMediaRecorder.release();
                mMediaRecorder = null;
            }
            //获取mic 分贝值
            getRecordDb();
        }

    }

    //获取分贝值
    public  void getRecordDb(){

        mRecordThread = new Thread(new Runnable() {
            @Override
            public void run() {
                Log.v(TAG, "get Db value Thread");
                CalculationDbValue();
                myHandler.sendEmptyMessageDelayed(VALUE,getValueTime);
            }
        });
        mRecordThread.start();

    }

   //计算分贝值 大小
    public void CalculationDbValue() {
        int BASE = 1;
        if (mMediaRecorder != null) {
            double ratio = (double) mMediaRecorder.getMaxAmplitude()/BASE;
            double db = 0;
            Log.v(TAG, "ratio  is:" + ratio);
            if (ratio > BASE) {
                db = 20 * Math.log10(ratio);
                dbValueSum = dbValueSum +db;
                getDbValueNum ++;
                //得到平均音量
                avg_db = dbValueSum/getDbValueNum;
                Log.v(TAG, "Db value is:" + db);
                Log.v(TAG, "avg Db value is:" + avg_db);
                if (db > max_db) {
                    max_db = db;
                    Log.d(TAG, "max Db is:" + max_db);
                }
            }
        }
    }

    private Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case VALUE:
                    getRecordDb();
                    break;

                default:
                    break;
            }
        }
    };


    /**
     * stopRecord.
     */
    public void stopRecord() {
        if (mMediaRecorder == null) {
            return;
        }
        try {
            mMediaRecorder.stop();
            mMediaRecorder.reset();
            mMediaRecorder.release();
            mMediaRecorder = null;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    //播放完成之后时间的监听
    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        Log.v(TAG,"play end");
        stopPlay();
        stopRecord();
        myHandler.removeMessages(VALUE);
        avg_View.setText(new DecimalFormat("0.00").format(avg_db));
        max_View.setText(new DecimalFormat("0.00").format(max_db));
    }


    @Override
    protected void onDestroy() {
        stopPlay();
        stopRecord();
        myHandler.removeMessages(VALUE);
        super.onDestroy();
    }
}

文件参考:

1、Android实时获取音量(单位:分贝)

2、android 获取实时麦克风声音大小
http://hw-hanwei-126-com.iteye.com/blog/2004861


【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月25日 0

暂无评论

推荐阅读
HvTJUzsxOBtS