MediaRecorder示例

Posted Welljia

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MediaRecorder示例相关的知识,希望对你有一定的参考价值。

MediaRecorder示例

基本流程

参考链接:https://developer.android.google.cn/guide/topics/media/camera#capture-video

具体步骤:

  1. 打开Camera,利用Camera.open()函数打开相机。

  2. 设置预览,把Camera和SurfaceView连接,利用Camera.setPreviewDisplay()设置预览的SurfaceHolder。

  3. 开始预览,调用Camera.startPreview()开始预览

  4. 开始录制视频(严格按照下面的顺序进行操作):
    a. unLock Camera,解锁相机,利用函数Camera.unlock(),这样Camera才能被MediaRecodrder使用,否则会报错。(从 android 4.0(API 级别 14)开始,系统将自动为您管理Camera.lock() 和 Camera.unlock() 调用。)
    b. 配置MediaRecorder,生成MediaRecorder实例

    • b.1 利用setCamera()设置Camera被视频录制使用
    • b.2 setAudiosource(),设置音频来自哪里(从哪里获取音频), MediaRecorder.AudioSource.CAMCORDER
    • b.3 setVideoSource() ,设置视频来源(从哪里获取视频),MediaRecorder.VideoSource.CAMERA
    • b.4 设置输出视频文件的格式和编码,从Android 2.2及以上版本开始,利用MediaRecorder.setProfile方法进行设置,利用CamcorderProfile.get()可以获取CamcorderProfile对象,内部包含了系统封装好的一些配置。
      至少需要设置的参数:
      setOutputFormat() 设置输出格式,一般设置为默认或者MediaRecorder.OutputFormat.MPEG_4.
      setAudioEncoder() 设置编码类型一般为默认或者MediaRecorder.AudioEncoder.AMR_NB.
      setVideoEncoder() 设置视频编码类型一般是默认或者MediaRecorder.VideoEncoder.MPEG_4_SP.
    • b.5 setOutputFile() 设置输出文件的存放位置。
    • b.6 setPreviewDisplay() ,设置预览的SurfaceHolder。

    c. 准备,调用MediaRecorder.prepare() 应用上面的配置。
    d. 开始视频录制,MediaRecorder.start()

  5. 停止录制
    a. 停止MediaRecorder,停止录制
    b. 重置 MediaRecorder.reset(),移除设置的参数
    c. 释放MediaRecorder
    d Lock Camera,Camera.lock(),从Android 4.0 开始,lock操作不是必须的,除非MediaRecorder.prepare()失败。

  6. Camera 停止预览,Camera.stopPreview().

  7. 释放Camera,Camera.release()。

代码说明

使用surfaceview时一直提示空指针报错,所以改成了TextureView。

录制前的关键函数如下:

private boolean prepareVideoRecorder() 

        // BEGIN_INCLUDE (configure_preview)
        mCamera = CameraHelper.getDefaultCameraInstance();

        // We need to make sure that our preview and recording video size are supported by the
        // camera. Query camera to find all the sizes and choose the optimal size given the
        // dimensions of our preview surface.
        Camera.Parameters parameters = mCamera.getParameters();
        List<Camera.Size> mSupportedPreviewSizes = parameters.getSupportedPreviewSizes();
        List<Camera.Size> mSupportedVideoSizes = parameters.getSupportedVideoSizes();
        Camera.Size optimalSize = CameraHelper.getOptimalVideoSize(mSupportedVideoSizes,
                mSupportedPreviewSizes, mPreview.getWidth(), mPreview.getHeight());

        // Use the same size for recording profile.
        CamcorderProfile profile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
        profile.videoFrameWidth = optimalSize.width;
        profile.videoFrameHeight = optimalSize.height;

        // likewise for the camera object itself.
        parameters.setPreviewSize(profile.videoFrameWidth, profile.videoFrameHeight);
        mCamera.setParameters(parameters);
        try 
            // Requires API level 11+, For backward compatibility use @link setPreviewDisplay
            // with @link SurfaceView
            mCamera.setPreviewTexture(mPreview.getSurfaceTexture());
         catch (IOException e) 
            Log.e(TAG, "Surface texture is unavailable or unsuitable" + e.getMessage());
            return false;
        
        // END_INCLUDE (configure_preview)


        // BEGIN_INCLUDE (configure_media_recorder)
        mMediaRecorder = new MediaRecorder();

        // Step 1: Unlock and set camera to MediaRecorder
        mCamera.unlock();
        mMediaRecorder.setCamera(mCamera);

        // Step 2: Set sources
        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
        mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

        // Step 3: Set a CamcorderProfile (requires API Level 8 or higher)
        mMediaRecorder.setProfile(profile);

        // Step 4: Set output file
        mOutputFile = CameraHelper.getOutputMediaFile(CameraHelper.MEDIA_TYPE_VIDEO);
        if (mOutputFile == null) 
            return false;
        
        mMediaRecorder.setOutputFile(mOutputFile.getPath());
        // END_INCLUDE (configure_media_recorder)

        // Step 5: Prepare configured MediaRecorder
        try 
            mMediaRecorder.prepare();
         catch (IllegalStateException e) 
            Log.d(TAG, "IllegalStateException preparing MediaRecorder: " + e.getMessage());
            releaseMediaRecorder();
            return false;
         catch (IOException e) 
            Log.d(TAG, "IOException preparing MediaRecorder: " + e.getMessage());
            releaseMediaRecorder();
            return false;
        
        return true;
    

而保存的路径,看如下代码:

// Step 4: Set output file
        mOutputFile = CameraHelper.getOutputMediaFile(CameraHelper.MEDIA_TYPE_VIDEO);
        if (mOutputFile == null) 
            return false;
        
        mMediaRecorder.setOutputFile(mOutputFile.getPath());
 java

这里CameraHelper是自定义的一个Camera工具类,其getOutputMediaFile的部分实现如下:

```java
    public  static File getOutputMediaFile(int type)
        // To be safe, you should check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this.
        if (!Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED)) 
            return  null;
        

        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES), "CameraSample");

这里可以看到是Environment.DIRECTORY_PICTURES,而这个的定义如下,所以保存的路径就是sdcard/Pictures/CameraSample下。

public class Environment 
    public static String DIRECTORY_ALARMS = "Alarms";
    public static String DIRECTORY_AUDIOBOOKS = "Audiobooks";
    public static String DIRECTORY_DCIM = "DCIM";
    public static String DIRECTORY_DOCUMENTS = "Documents";
    public static String DIRECTORY_DOWNLOADS = "Download";
    public static String DIRECTORY_MOVIES = "Movies";
    public static String DIRECTORY_MUSIC = "Music";
    public static String DIRECTORY_NOTIFICATIONS = "Notifications";
    public static String DIRECTORY_PICTURES = "Pictures";

以上是关于MediaRecorder示例的主要内容,如果未能解决你的问题,请参考以下文章

MediaRecorder示例

有人有 MediaRecorder 使用 ParcelFileDescriptor 和 createPipe() 吗?

Android:使用 MediaRecorder 录制音频 - 文件不播放

MediaRecorder的start()方法不能正常执行

Android MediaRecorder录制视频提示start failed的解决办法

Media Recorder 示例应用程序崩溃 - 为啥会这样?