Android 录制视频 Camera占用的解决方法

2,298 阅读2分钟
原文链接: www.zhangman523.cn

Android 录制视频 Camera占用的解决方法

最近需要修改项目中的视频录制功能,原来没怎么理会,可以正常录制。

但是不录制直接返回Camera就会出现占用情况,而且连系统相机都无法正常使用了。

只能重新手机,调试起来也比较麻烦。

最好发现 由于不当的调用

camera.lock()camera.unlock()导致的

看一看这两个方法的解释

 /**
     * Re-locks the camera to prevent other processes from accessing it.
     * Camera objects are locked by default unless {@link #unlock()} is
     * called.  Normally {@link #reconnect()} is used instead.
     *
     * <p>Since API level 14, camera is automatically locked for applications in
     * {@link android.media.MediaRecorder#start()}. Applications can use the
     * camera (ex: zoom) after recording starts. There is no need to call this
     * after recording starts or stops.
     *
     * <p>If you are not recording video, you probably do not need this method.
     *
     * @throws RuntimeException if the camera cannot be re-locked (for
     *     example, if the camera is still in use by another process).
     */
    public native final void lock();

lock()方法是一个native方法

注释的大概意思是

调用这个方法重新锁定相机以防止其他进程访问它。系统默认的状态就是locked状态,可以调用unlock()或者reconnect()来使用

还有注释说API 14 之后当你调用了MediaRecorder.start()方法lock()会自动调用。这就解释了为什么正常录制视频不会占用相机

看看另外一个方法

    /**
     * Unlocks the camera to allow another process to access it.
     * Normally, the camera is locked to the process with an active Camera
     * object until {@link #release()} is called.  To allow rapid handoff
     * between processes, you can call this method to release the camera
     * temporarily for another process to use; once the other process is done
     * you can call {@link #reconnect()} to reclaim the camera.
     *
     * <p>This must be done before calling
     * {@link android.media.MediaRecorder#setCamera(Camera)}. This cannot be
     * called after recording starts.
     *
     * <p>If you are not recording video, you probably do not need this method.
     *
     * @throws RuntimeException if the camera cannot be unlocked.
     */
    public native final void unlock();

这个注释写的很清楚了

调用unlock()方法允许其他进程使用,同时正在使用Cameralocked状态

还有调视频录制的时候必须先调unlock()然后在调MediaRecorder.setCamera(Camera)

总结

视频录制的步骤如下:

  • 调用unlock()方法
  • 调用MediaRecorder.setCamera(Camera)方法
  • 开始录制
  • 停止录制
  • 释放MediaRecorder
  • 调用lock()方法
  • 释放Camera

这就是完整的步骤了。

这里有个Demo可以参考一下GITHUB

转载请注明:zhangman523 » Android 录制视频 Camera占用的解决方法

喜欢 (1)