当前位置: 代码网 > it编程>App开发>Android > Android 实现录音和监听声音大小实现话筒动画效果

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

2024年08月02日 Android 我要评论
【代码】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)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com