The use of recording in Android

Today we introduce the application of recording in Android. In our development, there are often scenes that need to be recorded, such as voice recording, chatting and sending voice. In these cases, we have to perform recording operations. So today I will tell you how to record in Android.

1. Introduction to MediaRecorder

MediaRecorder is an audio and video recording tool that comes with Android. It completes media recording by manipulating the camera and microphone. It can record video and audio separately.

2. Common methods of MediaRecorder (common for recording and recording)

  • reset: Reset the recording resource.
  • prepare: prepare to record.
  • start: Start recording.
  • stop: End recording.
  • release: Release recording resources.
  • setOnErrorListener: Set the error listener. Can monitor server exceptions and unknown error events. Need to implement the onError method of the interface MediaRecorder.OnErrorListener.
  • setOnInfoListener: Set the information listener. You can monitor the recording end event, including reaching the recording duration or reaching the recording size. Need to implement the onInfo method of the interface MediaRecorder.OnInfoListener.
  • setMaxDuration: Set the maximum recording duration, in milliseconds.
  • setMaxFileSize: Set the maximum recordable file size, in bytes.
  • setOutputFile: Set the path of the output file.

3. MediaRecorder method for audio recording

  • setAudioSource: Set the audio source. The microphone AudioSource.MIC is generally used.
  • setOutputFormat: Set the media output format. See Table 1 for the value description of the media output format.
Table 1
The output format of the OutputFormat class Format classification extension name Format description
AMR_NB Audio .amr Narrowband format
AMR_WB Audio .amr Wideband format
AAC_ADTS Audio .aac Advanced audio transport stream format
MPEG_4 video .mp4 MPEG4 format
THREE_GPP video .3gp 3GP format
  • setAudioEncoder: Set the audio encoder. The value description of the audio encoder is shown in Table 2. Note: This method should be executed after the setOutputFormat method, otherwise an exception of setAudioEncoder called in an invalid state(2) will occur.
Table 2
Audio encoder of the AudioEncoder class Description
AMR_NB Narrowband coding
AMR_WB Wideband coding
AAC Advanced coding with low complexity
HE_AAC High-efficiency advanced coding
AAC_ELD Enhanced low-latency advanced coding
  • setAudioSamplingRate: Set the audio sampling rate in kilohertz (kHz). The AMR_NB format defaults to 8kHz, and the AMR_WB format defaults to 16kHz.
  • setAudioChannels: Set the number of audio channels. 1 means mono, 2 means dual channels.
  • setAudioEncodingBitRate: Set the number of bytes of audio recorded per second. The larger the value, the clearer the audio.

4. Audio recording example

Permission to add

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

Layout activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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/tv_record"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:text="录音"
        android:layout_centerInParent="true"
        android:background="@android:color/holo_green_light"
        android:gravity="center"/>
</RelativeLayout>

MainActivity.java

public class MainActivity extends WaterPermissionActivity implements MediaRecorder.OnErrorListener, MediaRecorder.OnInfoListener {

    private TextView tv_record;
    private MediaRecorder mMediaRecorder;
    private String voicePath;

    @Override
    protected MvcBaseModel getModelImp() {
        return null;
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initWidget() {
        tv_record = findViewById(R.id.tv_record);
        tv_record.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN){
                    //开始录制
                    tv_record.setText("松开停止");
                    requestPermission(WRITE_EXTERNAL_STORAGE);
                }else if (event.getAction() == MotionEvent.ACTION_UP){
                    //结束录制
                    tv_record.setText("录音");
                    cancelRecord();
                }
                return true;
            }
        });
    }

    @Override
    protected void doSDWrite() {
        requestPermission(READ_EXTERNAL_STORAGE);
    }

    @Override
    protected void doSDRead() {
        requestPermission(RECORD);
    }

    @Override
    protected void doRecord() {
        getPath();
        startRecord();
    }

    /**
     * 录制前创建一个空文件并获取路径
     */
    private void getPath(){
        List<String> list = new ArrayList<>();
        list.add("record");
        String dirPath = PathGetUtil.getLongwayPath(this,list);
        File fileDir = new File(dirPath);
        if (!fileDir.exists()){
            fileDir.mkdirs();
        }
        File fileVoice = new File(dirPath,"voice"+System.currentTimeMillis()+".amr");
        if (!fileVoice.exists()){
            try {
                fileVoice.createNewFile();
                voicePath = fileVoice.getPath();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 开始录音
     */
    private void startRecord(){
        //开始录音操作
        mMediaRecorder = new MediaRecorder(); // 创建一个媒体录制器
        mMediaRecorder.setOnErrorListener(this); // 设置媒体录制器的错误监听器
        mMediaRecorder.setOnInfoListener(this); // 设置媒体录制器的信息监听器
        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); // 设置音频源为麦克风
        mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB); // 设置媒体的输出格式
        mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); // 设置媒体的音频编码器
        // mMediaRecorder.setAudioSamplingRate(8); // 设置媒体的音频采样率。可选
        // mMediaRecorder.setAudioChannels(2); // 设置媒体的音频声道数。可选
        // mMediaRecorder.setAudioEncodingBitRate(1024); // 设置音频每秒录制的字节数。可选
        mMediaRecorder.setMaxDuration(10 * 1000); // 设置媒体的最大录制时长
        // mMediaRecorder.setMaxFileSize(1024*1024*10); // 设置媒体的最大文件大小
        // setMaxFileSize与setMaxDuration设置其一即可
        mMediaRecorder.setOutputFile(voicePath); // 设置媒体文件的保存路径
        try {
            mMediaRecorder.prepare(); // 媒体录制器准备就绪
            mMediaRecorder.start(); // 媒体录制器开始录制
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 取消录制操作
    private void cancelRecord() {
        if (mMediaRecorder != null) {
            mMediaRecorder.setOnErrorListener(null); // 错误监听器置空
            mMediaRecorder.setPreviewDisplay(null); // 预览界面置空
            try {
                mMediaRecorder.stop(); // 媒体录制器停止录制
            } catch (Exception e) {
                e.printStackTrace();
            }
            mMediaRecorder.release(); // 媒体录制器释放资源
            mMediaRecorder = null;
        }
    }

    @Override
    public void onError(MediaRecorder mr, int what, int extra) {
        if (mr != null) {
            mr.reset(); // 重置媒体录制器
        }
    }

    @Override
    public void onInfo(MediaRecorder mr, int what, int extra) {
        // 录制达到最大时长,或者达到文件大小限制,都停止录制
        if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED
                || what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED) {
            cancelRecord();
        }
    }
}

The old rules, dynamic permissions, everyone applies according to their own circumstances. Triggering to start recording is to execute two methods, getPath() and startRecord(), one is to obtain a new file path to play the audio file. The other is to start the actual recording. To stop recording, call the cancelRecord() method. Other processing can be configured according to the sample code. The parameters can be modified according to the actual situation of the project.

Guess you like

Origin blog.csdn.net/weixin_38322371/article/details/115212221