Android 实现录音和监听声音大小实现话筒动画效果

Android 实现录音和监听声音大小实现话筒动画效果

主要就一个Dialog:

package com.coodays.wecare.telephone;

import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.media.MediaRecorder;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.coodays.wecare.R;

import java.io.File;
import java.util.Random;

public class RecordDialog extends Dialog {
    protected Context mContext;

    protected WindowManager.LayoutParams mLayoutParams;

    //存储很多张话筒图片的数组
    private Drawable[] micImages;
    //话筒的图片
    private ImageView micImage;
    //到计时时间
    TextView recording_hint;

    private MediaRecorder recorder = null;
    //录音存储在SD卡的路径
    private String output_Path = Environment.getExternalStorageDirectory().getAbsolutePath()
            + File.separator + "luyin.3gp";
    //录音文件
    private File soundFile;
    private int BASE = 600;
    private int SPACE = 200;// 间隔取样时间

    public WindowManager.LayoutParams getLayoutParams() {
        return mLayoutParams;
    }

    public RecordDialog(@NonNull Context context) {
        super(context);
        initView(context);
    }

    public RecordDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
        initView(context);
    }

    protected RecordDialog(@NonNull Context context, boolean cancelable, @Nullable OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
        initView(context);
    }

    private void initView(Context context) {
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setBackgroundDrawableResource(R.drawable.transparent_bg);
        mContext = context;
        Window window = this.getWindow();
        mLayoutParams = window.getAttributes();
        mLayoutParams.alpha = 1f;
        window.setAttributes(mLayoutParams);
        if (mLayoutParams != null) {
            mLayoutParams.height = android.view.ViewGroup.LayoutParams.MATCH_PARENT;
            mLayoutParams.gravity = Gravity.CENTER;
        }

        View dialogView = LayoutInflater.from(getContext()).inflate(R.layout.dialog_record, null);
        setContentView(dialogView);
        micImage = (ImageView) dialogView.findViewById(R.id.mic_image);
        recording_hint = (TextView) dialogView.findViewById(R.id.recording_hint);
        micImages = new Drawable[]{
                getContext().getResources().getDrawable(R.drawable.record_fps1),
                getContext().getResources().getDrawable(R.drawable.record_fps2),
                getContext().getResources().getDrawable(R.drawable.record_fps3),
                getContext().getResources().getDrawable(R.drawable.record_fps4),
                getContext().getResources().getDrawable(R.drawable.record_fps5),
                getContext().getResources().getDrawable(R.drawable.record_fps6),
                getContext().getResources().getDrawable(R.drawable.record_fps7),
                getContext().getResources().getDrawable(R.drawable.record_fps8),
                getContext().getResources().getDrawable(R.drawable.record_fps9),};
        CountDownTimer timer = new CountDownTimer(10*1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                // TODO Auto-generated method stub
                recording_hint.setText("还剩"+millisUntilFinished/1000+"秒");
            }

            @Override
            public void onFinish() {
                recording_hint.setText("倒计时完毕了");
                stopRecoder();
                Toast.makeText(getContext(), "录音存储到了"+soundFile.getAbsolutePath(), 1).show();
            }
        }.start();
        startRecord();
    }


    void startRecord(){
        if (!isExitsSdcard()) {
            Toast.makeText(getContext(), "未检测到SD卡", Toast.LENGTH_SHORT).show();
            return;
        }
        if(recorder!=null){
            recorder.stop();
            recorder.release();
            recorder=null;
        }
        soundFile=new File(output_Path);
        recorder=new MediaRecorder();
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);//声音来源是话筒
        recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);//设置格式
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);//设置解码方式
        recorder.setOutputFile(soundFile.getAbsolutePath());
        try {
            recorder.prepare();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         recorder.start();
        updateMicStatus();
//        update();
    }

    /**
     * 按住说话listener
     *
     */
    /*class PressToSpeakListen implements View.OnTouchListener {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    if (!isExitsSdcard()) {
                        Toast.makeText(MainActivity.this, "未检测到SD卡", Toast.LENGTH_SHORT).show();
                        return false;
                    }
                    if(recorder!=null){
                        recorder.stop();
                        recorder.release();
                        recorder=null;
                    }
                    soundFile=new File(output_Path);
                    recorder=new MediaRecorder();
                    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);//声音来源是话筒
                    recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);//设置格式
                    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);//设置解码方式
                    recorder.setOutputFile(soundFile.getAbsolutePath());
                    try {
                        recorder.prepare();
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    recorder.start();
                    updateMicStatus();
                    recordingContainer.setVisibility(View.VISIBLE);
                    recordingHint.setText("手指上滑,取消发送");
                    recordingHint.setBackgroundColor(Color.TRANSPARENT);
                    return true;
                case MotionEvent.ACTION_MOVE: {
                    //在这里只是做了监听,并没有做与发送相关的处理
                    if (event.getY() < 0) {
                        recordingHint.setText("松开手指,取消发送");
                        recordingHint.setBackgroundResource(R.drawable.recording_text_hint_bg);

                    } else {
                        recordingHint.setText("手指上滑,取消发送");
                        recordingHint.setBackgroundColor(Color.TRANSPARENT);

                    }
                    return true;
                }
                case MotionEvent.ACTION_UP:
                    //抬起手指,停止录音
                    recordingContainer.setVisibility(View.INVISIBLE);
                    stopRecoder();
                    Toast.makeText(getApplicationContext(), "录音存储到了"+soundFile.getAbsolutePath(), 1).show();
                    return true;
                default:

                    return false;
            }
        }
    }*/

    private void stopRecoder(){
        if (soundFile != null && soundFile.exists())
        {
            // 停止录音
            recorder.stop();
            // 释放资源
            recorder.release();
            recorder = null;
        }
    }

    private void updateMicStatus() {
        if (recorder != null) {
            int ratio = recorder.getMaxAmplitude() / BASE;
            int db = 0;// 分贝
            if (ratio > 1)
                db = (int) (20 * Math.log10(ratio));
            System.out.println("分贝值:" + db + "     " + Math.log10(ratio));
            //我对着手机说话声音最大的时候,db达到了35左右,
            mHandler.postDelayed(mUpdateMicStatusTimer, SPACE);
            //所以除了2,为的就是对应14张图片
            mHandler.sendEmptyMessage(db / 2);
        }
    }

    int i = 0;
    private void update(){
        i = 0;
        for (;i<500;i++){
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mHandler.sendEmptyMessage(i);
                }
            },200);
        }
    }

    private Runnable mUpdateMicStatusTimer = new Runnable() {
        public void run() {
            updateMicStatus();
        }
    };

    private final Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            int what = msg.what;
            //根据mHandler发送what的大小决定话筒的图片是哪一张
            //说话声音越大,发送过来what值越大
            if (what > 8) {
                what = new Random().nextInt(8);
            }
            micImage.setImageDrawable(micImages[what]);
        }
    };

    /**
     * 检测Sdcard是否存在
     *
     * @return
     */
    public boolean isExitsSdcard() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
            return true;
        else
            return false;
    }
} 

dialog_record.xml为:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginBottom="10dp"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:background="@drawable/transparent_bg"
    android:orientation="vertical">

    <RelativeLayout
        android:id="@+id/recording_container"
        android:layout_width="match_parent"
        android:layout_height="@dimen/widget_size_90"
        android:padding="10dp"
        android:gravity="center"
        android:background="@color/white"
        android:visibility="visible">

        <ImageView
            android:id="@+id/mic_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:src="@drawable/record_fps1" />

        <TextView
            android:id="@+id/recording_hint"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/mic_image"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="10dp"
            android:padding="2dp"
            android:text="10s"
            android:textSize="10sp" />
    </RelativeLayout>
</LinearLayout>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值