Android 使用MediaRecorder实现录音

Android开发中,实现录音的方式主要有两种:MediaRecorderAudioRecord

两者区别在于MediaRecorder录制的文件是经过压缩的,需要设置编码器,录制的文件系统可以直接播放。

而AudioRecord录制的是PCM格式的文件,录制的文件没有经过编码,需要使用AudioTrack播放。

使用步骤

一、添加权限

添加录音胡权限:

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

RECORD_AUDIO属于运行时权限,申请权限:

 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 1);

二、创建 MediaRecorder 对象

2.1、创建MediaRecorder对象
    private MediaRecorder mRecorder;
    
    mRecorder = new MediaRecorder();
2.2、设置音频源 setAudioSource
//MIC 麦克风音频源
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);

可选的音频源在 AudioSource 中有:

    public final class AudioSource {

        private AudioSource() {}
        /** @hide */
        public final static int AUDIO_SOURCE_INVALID = -1;
        /** 默认音频 **/
        public static final int DEFAULT = 0;
        /** 麦克风 */
        public static final int MIC = 1;

        /** Voice call uplink (Tx) audio source.
         * 语音呼叫上行(Tx)音频源
         */
        public static final int VOICE_UPLINK = 2;

        /** Voice call downlink (Rx) audio source.
         *  语音呼叫下行(Rx)音频源。
         */
        public static final int VOICE_DOWNLINK = 3;

        /** Voice call uplink + downlink audio source
         *  语音通话上行+下行音频源
         */
        public static final int VOICE_CALL = 4;

        /** Microphone audio source tuned for video recording, with the same orientation
         *  as the camera if available. */
        public static final int CAMCORDER = 5;

        /** 麦克风音频源进行了语音识别. */
        public static final int VOICE_RECOGNITION = 6;

        /** Microphone audio source tuned for voice communications such as VoIP. It
         *  will for instance take advantage of echo cancellation or automatic gain control
         *  if available.
         */
        public static final int VOICE_COMMUNICATION = 7;

        /**
         * 用于远程呈现音频流子混合的音频源。
         */
        @RequiresPermission(android.Manifest.permission.CAPTURE_AUDIO_OUTPUT)
        public static final int REMOTE_SUBMIX = 8;

        /** 麦克风原始音频
         *  {@link #DEFAULT} otherwise. */
        public static final int UNPROCESSED = 9;

        /**
         * Audio source for capturing broadcast radio tuner output.
         * @hide
         */
        @SystemApi
        public static final int RADIO_TUNER = 1998;

        /**
         * Audio source for preemptible, low-priority software hotword detection
         */
        @SystemApi
        @RequiresPermission(android.Manifest.permission.CAPTURE_AUDIO_HOTWORD)
        public static final int HOTWORD = 1999;
    }
2.3、设置输出格式: setOutputFormat
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);

可选输出格式有:

    public final class OutputFormat {
        private OutputFormat() {}
        public static final int DEFAULT = 0;
        /** 3GPP media file format*/
        public static final int THREE_GPP = 1;
        /** MPEG4 media file format*/
        public static final int MPEG_4 = 2;
        /** The following formats are audio only .aac or .amr formats */
        /**
         * AMR NB file format
         * @deprecated  Deprecated in favor of MediaRecorder.OutputFormat.AMR_NB
         */
        public static final int RAW_AMR = 3;
        /** AMR NB file format */
        public static final int AMR_NB = 3;
        /** AMR WB file format */
        public static final int AMR_WB = 4;
        /** @hide AAC ADIF file format */
        public static final int AAC_ADIF = 5;
        /** AAC ADTS file format */
        public static final int AAC_ADTS = 6;
        /** @hide Stream over a socket, limited to a single stream */
        public static final int OUTPUT_FORMAT_RTP_AVP = 7;
        /** H.264/AAC data encapsulated in MPEG2/TS */
        public static final int MPEG_2_TS = 8;
        /** VP8/VORBIS data in a WEBM container */
        public static final int WEBM = 9;
    };
2.4、设置输出文件名 setOutputFile
		String mFileName = getExternalCacheDir().getAbsolutePath() + "/audio_test.3gp";
        mRecorder.setOutputFile(mFileName);
2.5、设置音频编码 setAudioEncoder
     mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

可选编码有:

    public final class AudioEncoder {
        private AudioEncoder() {}
        public static final int DEFAULT = 0;
        /** AMR (Narrowband) audio codec */
        public static final int AMR_NB = 1;
        /** AMR (Wideband) audio codec */
        public static final int AMR_WB = 2;
        /** AAC Low Complexity (AAC-LC) audio codec */
        public static final int AAC = 3;
        /** High Efficiency AAC (HE-AAC) audio codec */
        public static final int HE_AAC = 4;
        /** Enhanced Low Delay AAC (AAC-ELD) audio codec */
        public static final int AAC_ELD = 5;
        /** Ogg Vorbis audio codec */
        public static final int VORBIS = 6;
    }

三、准备录制(prepare()、start())

录制前需要调用prepare()方法

    private void startRecord() {
        mRecorder = new MediaRecorder();
        //设置录入音频源
        //MIC 麦克风音频源
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        //设置输出格式
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        //设置输出文件
        mRecorder.setOutputFile(mFileName);
        //设置音频编码
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        //准备编码
        try {
            mRecorder.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //开始录制
        mRecorder.start();
        mRecorder.setOnErrorListener(new MediaRecorder.OnErrorListener() {
            @Override
            public void onError(MediaRecorder mr, int what, int extra) {
                //mRecorder.reset();
                Log.e("tag", "zzy:  录制出错");
            }
        });
    }

四、停止录制 stop()

     mRecorder.stop();

五、播放音频

播放的话可以找到录制的文件进行播放,也可以使用MediaPlayer进行播放

	//初始化
	MediaPlayer mPlayer;
	mPlayer = new MediaPlayer();
	mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            mPlayer.start();
        }
    });
	//点击播放
    mPlayer.setDataSource(mFileName);
    mPlayer.prepareAsync();

MediaRecorder 用法还是很简单的,更多的用例可以到官网上查看

参考: https://developer.android.google.cn/guide/topics/media/mediarecorder?hl=zh_cn

你可能感兴趣的:(多媒体开发)