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

原文 https://www.zhangman523.cn/361.html

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

但是不录制直接返回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

原文 https://www.zhangman523.cn/361.html

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 以下内容翻译来源,Google官方开发文档:https://developer.android.google.cn...
    肱二头肌的孤单阅读 5,298评论 5 47
  • 设置权限 如果要在App中使用摄像头,必须先在Manifest中声明摄像头权限 以及声明应用需要有摄像头 如果摄像...
    Mob_Developer阅读 13,519评论 1 18
  • 转载请注明出处(https://www.jianshu.com/p/5f538820e370),您的打赏是小编继续...
    福later阅读 28,169评论 8 73
  • 2017.8.6 14:00 你和这个世界没有多大联系,死了也没有什么多大关系,生死本没有什么不同。活着,因为有...
    聿亦非阅读 292评论 0 0
  • 此时正在陪爷爷输液,虽然医院有点嘈杂,好像不适合写作,但是还是想写点什么! 八月八号 下午一...
    苏陌彤阅读 698评论 4 1