Android 錄製視訊 Camera佔用的解決方法
原文ofollow,noindex">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()
方法允許其他程序使用,同時正在使用Camera
是locked
狀態
還有調視訊錄製的時候必須先調unlock()
然後在調MediaRecorder.setCamera(Camera)
總結
視訊錄製的步驟如下:
unlock() MediaRecorder.setCamera(Camera) MediaRecorder lock() Camera
這就是完整的步驟了。