当前位置 主页 > 网站技术 > 代码类 >

    Android仿微信录音功能(录音后的raw文件转mp3文件)

    栏目:代码类 时间:2019-11-18 15:09

    现在很多时候需要用到录音,然后如果我们的App是ios和android两端的话,就要考虑录音的文件在两端都能使用,这个时候就需要适配,两端的录音文件都要是mp3文件,这样才能保证两边都能播放。

    针对这个,封装了一个简单可用的录音控件。

    使用方法:

    1.在xml文件中添加

    <ant.muxi.com.audiodemo.view.SoundTextView
     android:
     android:text="按住开始录音"
     android:gravity="center"
     android:background="@drawable/bg_round_black"
     android:layout_marginLeft="20dp"
     android:layout_marginRight="20dp"
     android:layout_marginBottom="40px"
     android:padding="20px"
     android:layout_width="match_parent"
     android:layout_height="wrap_content">
     </ant.muxi.com.audiodemo.view.SoundTextView>

    2.别忘了申请录音权限

    AndPermission.with(MainActivity.this)
      .permission(Manifest.permission.RECORD_AUDIO,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE)
      .onGranted(permissions -> {
       showSelect();
      })
      .onDenied(permissions -> {
       Toast.makeText(MainActivity.this,"请同意录音权限",Toast.LENGTH_SHORT).show();
      })
      .start();
    private void showSelect() {
     SoundTextView recordAudio = findViewById(R.id.record_audio);
     recordAudio.setOnRecordFinishedListener(new SoundTextView.OnRecordFinishedListener() {
      @Override
      public void newMessage(String path, int duration) {
      int index = path.lastIndexOf("/");
      String fileName = path.substring(index + 1);
      Log.e("录音文件", "path=: "+path );
      }
     });
     }

    使用方法如上非常简单:

    主要的类

    package ant.muxi.com.audiodemo.view;
     import android.app.Activity;
    import android.app.Dialog;
    import android.content.Context;
    import android.os.Environment;
    import android.os.Handler;
    import android.os.Message;
    import android.util.AttributeSet;
    import android.util.Log;
    import android.view.MotionEvent;
    import android.widget.TextView;
    import android.widget.Toast;
    import androidx.appcompat.widget.AppCompatTextView;
    import java.io.File;
    import ant.muxi.com.audiodemo.R;
    import ant.muxi.com.audiodemo.audio.ProgressTextUtils;
    import ant.muxi.com.audiodemo.audio.RecordManager;
    public class SoundTextView extends AppCompatTextView {
     private Context mContext;
     private Dialog recordIndicator;
     private TextView mVoiceTime;
     private File file;
     private String type = "1";//默认开始录音 type=2,录音完毕
     RecordManager recordManager;
     File fileto;
     int level;
     private long downT;
     String sountime;
     public SoundTextView(Context context) {
     super(context);
     init();
     }
     public SoundTextView(Context context, AttributeSet attrs, int defStyle) {
     super(context, attrs, defStyle);
     this.mContext = context;
     init();
     }
     public SoundTextView(Context context, AttributeSet attrs) {
     super(context, attrs);
     this.mContext = context;
     init();
     }
     private void init() {
     recordIndicator = new Dialog(getContext(), R.style.jmui_record_voice_dialog);
     recordIndicator.setContentView(R.layout.jmui_dialog_record_voice);
     mVoiceTime = (TextView) recordIndicator.findViewById(R.id.voice_time);
     file = new File(Environment.getExternalStorageDirectory() + "/recoder.amr");
     fileto = new File(Environment.getExternalStorageDirectory() + "/recoder.mp3");
     recordManager = new RecordManager(
      (Activity) mContext,
      String.valueOf(file),
      String.valueOf(fileto));
     recordManager.setOnAudioStatusUpdateListener(new RecordManager.OnAudioStatusUpdateListener() {
      @Override
      public void onUpdate(double db) {
      //得到分贝
      if (null != recordIndicator) {
       level = (int) db;
       handler.sendEmptyMessage(0x111);
      }
      }
     });
     }
     Handler handler = new Handler() {
     @Override
     public void handleMessage(Message msg) {
      super.handleMessage(msg);
      switch (msg.what) {
      case 0x111:
       sountime = ProgressTextUtils.getSecsProgress(System.currentTimeMillis() - downT);
       long time = System.currentTimeMillis() - downT;
       mVoiceTime.setText(ProgressTextUtils.getProgressText(time));
       //判断时间
       judetime(Integer.parseInt(sountime));
       break;
      }
     }
     };
     public void judetime(int time) {
     if (time > 14) {
      //结束录制
      Toast.makeText(mContext, "录音不能超过十五秒", Toast.LENGTH_SHORT).show();
      recordManager.stop_mp3();
      new Thread() {
      @Override
      public void run() {
       super.run();
       recordManager.saveData();
       finishRecord(fileto.getPath(), sountime);
      }
      }.start();
      recordIndicator.dismiss();
      type = "2";
     }
     }
     @Override
     public boolean onTouchEvent(MotionEvent event) {
     int action = event.getAction();
     switch (action) {
      case MotionEvent.ACTION_DOWN:
      if (type.equals("1")) {
       //开始发送时间
       downT = System.currentTimeMillis();
       recordManager.start_mp3();
       recordIndicator.show();
      } else {
       Log.e("-log-", "您已经录制完毕: ");
      }
      return true;
      case MotionEvent.ACTION_UP:
      if (type.equals("1")) {
       try {
       if (Integer.parseInt(sountime) > 2) {
        recordManager.stop_mp3();
        new Thread() {
        @Override
        public void run() {
         super.run();
         recordManager.saveData();
         finishRecord(fileto.getPath(), sountime);
        }
        }.start();
        if (recordIndicator.isShowing()) {
        recordIndicator.dismiss();
        }
        type = "2";
       } else {
        recordManager.stop_mp3();
        if (recordIndicator.isShowing()) {
        recordIndicator.dismiss();
        }
        sountime = null;
        Toast.makeText(mContext, "录音时间少于3秒,请重新录制", Toast.LENGTH_SHORT).show();
       }
       } catch (Exception e) {
       recordManager.stop_mp3();
       if (recordIndicator.isShowing()) {
        recordIndicator.dismiss();
       }
       sountime = null;
       Toast.makeText(mContext, "录音时间少于3秒,请重新录制", Toast.LENGTH_SHORT).show();
       }
      }
      break;
      case MotionEvent.ACTION_CANCEL:
      if (recordIndicator.isShowing()) {
       recordIndicator.dismiss();
      }
      break;
     }
     return super.onTouchEvent(event);
     }
     //录音完毕加载 ListView item
     private void finishRecord(String path, String time) {
     if (onRecordFinishedListener != null) {
      onRecordFinishedListener.newMessage(path, Integer.parseInt(time));
      type = "1";
     }
     //发送语音
     // Toasts.toast(getContext(),"您已经录完了一条语音"+myRecAudioFile);
     }
     private OnRecordFinishedListener onRecordFinishedListener;
     public void setOnRecordFinishedListener(OnRecordFinishedListener onRecordFinishedListener) {
     this.onRecordFinishedListener = onRecordFinishedListener;
     }
     public interface OnRecordFinishedListener {
     void newMessage(String path, int duration);
     }
    }