自学 Android 关于MediaRecorder的对象复用

目录

一、MediaRecorder 概览

二、权限申请

1、清单注册

2、动态申请

三、MediaRecorder的使用

1、控件的监听

2、开始录音

3、结束录音

4、重点分析


一、MediaRecorder 概览

Android 多媒体框架支持捕获和编码各种常见的音频和视频格式。如果设备硬件支持,您可以使用 MediaRecorder API。

本文档向您介绍如何使用 MediaRecorder 编写能够从设备麦克风捕获音频、保存音频并(使用 MediaPlayer)进行播放的应用。要录制视频,您需要使用设备的摄像头以及 。具体说明请参阅相机指南。

注意:Android 模拟器无法录制音频。请务必在能够录制音频的真实设备上测试您的代码。

二、权限申请

1、清单注册

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

2、动态申请

int hasWriteStoragePermission = ContextCompat.checkSelfPermission(getApplication(), Manifest.permission.RECORD_AUDIO);
        if (hasWriteStoragePermission == PackageManager.PERMISSION_GRANTED) {
            //拥有权限,执行操作
            init();
        }else{
            //没有权限,向用户请求权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 0x20);
        }

三、MediaRecorder的使用

1、控件的监听

//这个是例子代码
tv_recording.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        Log.d("按下","开始");
                        startAudio();
                        break;
                    case MotionEvent.ACTION_UP:
                        Log.d("松开","结束");
                        endAudio();
                        break;
                }

                return true;
            }
        });

2、开始录音

 //开始录音准备
private void startAudio() {
        if (mediaRecorder == null) {
            mediaRecorder = new MediaRecorder();
        }else {
            mediaRecorder.reset();
        }
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.AAC_ADTS);
        mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        mediaRecorder.setAudioSamplingRate(64 * 1000);  //采样率
        mediaRecorder.setAudioEncodingBitRate(96 * 1000); //编码率
        String name = "voice_" + System.currentTimeMillis() + ".aac";
        String files = getExternalFilesDir(null).getAbsolutePath() + "/" + name;
        File file = new File(files);
        if (!file.exists()) {
            file.getParentFile().mkdirs();
        }
        mediaRecorder.setOutputFile(files);
        try {
            mediaRecorder.prepare();
            mediaRecorder.start();
        } catch (IOException e) {
            e.printStackTrace();
            mediaRecorder.reset();
        }
        urlList.add(name);
        adaper.notifyDataSetChanged();
    }

3、结束录音

//结束录音
private void endAudio() {
        if (mediaRecorder != null) {
            mediaRecorder.stop();
            mediaRecorder.reset();
        }
    }

4、重点分析

MediaRecorder:reset()

/**
 * Restarts the MediaRecorder to its idle state. After calling
 * this method, you will have to configure it again as if it had just been
 * constructed.
 */
public void reset() {
    native_reset();

    // make sure none of the listeners get called anymore
    mEventHandler.removeCallbacksAndMessages(null);
}

大概意思:/**

      *将 MediaRecorder 重新启动到其空闲状态。 调用后
      * 这种方法,你将不得不重新配置它,就像它刚刚配置的一样
      * 建。

*/

MediaRecorder:release()

/**
     * Releases resources associated with this MediaRecorder object.
     * It is good practice to call this method when you're done
     * using the MediaRecorder. In particular, whenever an Activity
     * of an application is paused (its onPause() method is called),
     * or stopped (its onStop() method is called), this method should be
     * invoked to release the MediaRecorder object, unless the application
     * has a special need to keep the object around. In addition to
     * unnecessary resources (such as memory and instances of codecs)
     * being held, failure to call this method immediately if a
     * MediaRecorder object is no longer needed may also lead to
     * continuous battery consumption for mobile devices, and recording
     * failure for other applications if no multiple instances of the
     * same codec are supported on a device. Even if multiple instances
     * of the same codec are supported, some performance degradation
     * may be expected when unnecessary multiple instances are used
     * at the same time.
     */
    public native void release();

大概意思:/**
     * 释放与此 MediaRecorder 对象关联的资源。
     * 完成后调用此方法是一个好习惯
     * 使用 MediaRecorder。特别是,每当一个 Activity
     * 应用程序已暂停(调用其 onPause() 方法),
     * 或停止(它的 onStop() 方法被调用),这个方法应该是
     * 调用以释放 MediaRecorder 对象,除非应用程序
     * 有一个特殊的需要保持对象周围。此外
     * 不必要的资源(例如内存和编解码器实例)
     * 被搁置,如果出现以下情况,则无法立即调用此方法
     * 不再需要 MediaRecorder 对象也可能导致
     * 移动设备的持续电池消耗和录音
     * 如果没有多个实例,其他应用程序将失败
     * 设备支持相同的编解码器。即使多个实例
     * 支持相同编解码器,性能有所下降
     * 使用不必要的多个实例时可能会出现
     * 同时。
     */

注意:现在大部分的教材都是只有release()这个释放方法没有reset(), 所以造成MediaRecorder对象不能复用的印象,但是一定记得最后release()这个释放资源,记得是最后调用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值