How to get camera preview frame after every 500ms

后端 未结 2 530
暖寄归人
暖寄归人 2021-01-25 20:53

I am developing sample application which gives me color code of pointed image or object via Camera in android. My application is similar to this application and I am using this

相关标签:
2条回答
  • 2021-01-25 21:08

    You can calculate the elapsed time in onPreviewFrame(). For example:

        boolean isFirstTime = true;
        long startTime = 0;
        PreviewCallback callback = new PreviewCallback() {
            @Override
            public void onPreviewFrame(byte[] data, Camera camera) {
                // TODO Auto-generated method stub
                if (isFirstTime) {
                    isFirstTime = false;
                    startTime = SystemClock.currentThreadTimeMillis();
                    decodeYUV420SP(pixels, data, previewSize.width,  previewSize.height);  
                    listener.OnPreviewUpdated(pixels, previewSize.width, previewSize.height);
                }
                else {
                    long currentTime = SystemClock.currentThreadTimeMillis();
                    long elapsedTime = currentTime - startTime;
                    if (elapsedTime >= 500) { // trigger your event
                        startTime = currentTime;
                        decodeYUV420SP(pixels, data, previewSize.width,  previewSize.height);  
                        listener.OnPreviewUpdated(pixels, previewSize.width, previewSize.height);
                    }
                }
            }
        };
    

    Do not forget to reset the boolean value and start time when you switch the preview status.

    0 讨论(0)
  • 2021-01-25 21:21

    Nothing will guarantee precise 500ms - camera hardware is not set to respond immediately. Still, you can be rather close to that. First of all, open the camera from a background Handler thread (see https://stackoverflow.com/a/19154438/192373).

    public void onPreviewFrame(byte[] data, Camera camera) {
        long releaseTime = SystemClock.currentThreadTimeMillis() + 500;
        decodeYUV420SP(pixels, data, previewSize.width,  previewSize.height);  
        listener.OnPreviewUpdated(pixels, previewSize.width, previewSize.height);
        resetBuffer();
        SystemClock.sleep(releaseTime-SystemClock.currentThreadTimeMillis());
    }
    

    This assumes that decodeYUV420SP() and OnPreviewUpdated() together take much less than 500ms.

    0 讨论(0)
提交回复
热议问题