Android UBS摄像头,最简单的使用教程,UVC,USBCamera

这可能是史上最简单的UBS摄像头教程了,全程不过200行代码。

附上Project GitHub地址

https://github.com/wechat-AmosCC/AndroidUSBCamera


1,在项目中导入楼主编的libusbcamera-release.aar

implementation (name:'libusbcamera-release',ext:'aar')

2,在项目中引入日本友人的

api("com.serenegiant:common:2.12.4") {

excludemodule:'support-v4'

}

3,在你的Android项目中开始愉快的使用吧

3.1 XML布局文件先添加

<com.serenegiant.usb.widget.UVCCameraTextureView>

3.2 .java中

extends AppCompatActivityimplements CameraDialog.CameraDialogParent, CameraViewInterface.Callback

实现CameraDialog,和CameraViewInterface

3.3 使用

mUVCCameraView = findViewById(R.id.camera_view);

mUVCCameraView.setCallback(this);

mCameraHelper = UVCCameraHelper.getInstance();

mCameraHelper.setDefaultFrameFormat(UVCCameraHelper.FRAME_FORMAT_MJPEG);

mCameraHelper.initUSBMonitor(this,mUVCCameraView,listener);

mCameraHelper.setOnPreviewFrameListener(new AbstractUVCCameraHandler.OnPreViewResultListener() {

@Override

    public void onPreviewResult(byte[] nv21Yuv) {

}

});

3.4 项目要添加存储读写权限。

3.5 完整的class

package gittest.uvc.amos.codes.com.uvcgittest;

import android.Manifest;

import android.content.pm.PackageManager;

import android.hardware.usb.UsbDevice;

import android.os.Looper;

import android.support.annotation.NonNull;

import android.support.v4.app.ActivityCompat;

import android.support.v4.content.ContextCompat;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.util.Log;

import android.view.Surface;

import android.view.View;

import android.widget.Button;

import android.widget.Toast;

import com.amos.codes.uvc.FileUtils;

import com.amos.codes.uvc.UVCCameraHelper;

import com.serenegiant.usb.CameraDialog;

import com.serenegiant.usb.USBMonitor;

import com.serenegiant.usb.common.AbstractUVCCameraHandler;

import com.serenegiant.usb.encoder.RecordParams;

import com.serenegiant.usb.widget.CameraViewInterface;

import java.util.ArrayList;

import java.util.List;

public class MainActivityextends AppCompatActivityimplements CameraDialog.CameraDialogParent, CameraViewInterface.Callback{

private ButtonbtnPhoto,btnStartRec,btnStopRec,btnRotate;

private UVCCameraHelpermCameraHelper;

private CameraViewInterfacemUVCCameraView;

private boolean isRequest;

private boolean isPreview;

private UVCCameraHelper.OnMyDevConnectListenerlistener =new UVCCameraHelper.OnMyDevConnectListener() {

@Override

        public void onAttachDev(UsbDevice device) {

// request open permission

            if (!isRequest) {

isRequest =true;

if (mCameraHelper !=null) {

mCameraHelper.requestPermission(0);

}

}

}

@Override

        public void onDettachDev(UsbDevice device) {

// close camera

            if (isRequest) {

isRequest =false;

mCameraHelper.closeCamera();

showShortMsg(device.getDeviceName() +" is out");

}

}

@Override

        public void onConnectDev(UsbDevice device,boolean isConnected) {

if (!isConnected) {

showShortMsg("fail to connect,please check resolution params");

isPreview =false;

}else {

isPreview =true;

showShortMsg("connecting");

new Thread(new Runnable() {

@Override

                    public void run() {

try {

Thread.sleep(2500);

}catch (InterruptedException e) {

e.printStackTrace();

}

Looper.prepare();

if(mCameraHelper !=null &&mCameraHelper.isCameraOpened()) {

}

Looper.loop();

}

}).start();

}

}

@Override

        public void onDisConnectDev(UsbDevice device) {

showShortMsg("disconnecting");

}

};

String[]permissions =new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};

ListmPermissionList =new ArrayList<>();

private static final int PERMISSION_REQUEST =1;

private void checkPermission() {

mPermissionList.clear();

//判断哪些权限未授予

        for (int i =0; i

if (ContextCompat.checkSelfPermission(this,permissions[i]) != PackageManager.PERMISSION_GRANTED) {

mPermissionList.add(permissions[i]);

}

}

/**

* 判断是否为空

*/

        if (mPermissionList.isEmpty()) {//未授予的权限为空,表示都授予了

        }else {//请求权限方法

            String[] permissions =mPermissionList.toArray(new String[mPermissionList.size()]);//将List转为数组

            ActivityCompat.requestPermissions(this, permissions,PERMISSION_REQUEST);

}

}

/**

* 响应授权

* 这里不管用户是否拒绝,都进入首页,不再重复申请权限

*/

    @Override

    public void onRequestPermissionsResult(int requestCode,@NonNull String[] permissions,@NonNull int[] grantResults) {

super.onRequestPermissionsResult(requestCode, permissions, grantResults);

switch (requestCode) {

case PERMISSION_REQUEST:

break;

default:

super.onRequestPermissionsResult(requestCode, permissions, grantResults);

break;

}

}

private void showShortMsg(String msg) {

Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();

}

@Override

    protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

initButtons();

checkPermission();

mUVCCameraView = findViewById(R.id.camera_view);

mUVCCameraView.setCallback(this);

mCameraHelper = UVCCameraHelper.getInstance();

mCameraHelper.setDefaultFrameFormat(UVCCameraHelper.FRAME_FORMAT_MJPEG);

mCameraHelper.initUSBMonitor(this,mUVCCameraView,listener);

mCameraHelper.setOnPreviewFrameListener(new AbstractUVCCameraHandler.OnPreViewResultListener() {

@Override

            public void onPreviewResult(byte[] nv21Yuv) {

}

});

}

@Override

    protected void onStart() {

super.onStart();

// step.2 register USB event broadcast

        if (mCameraHelper !=null) {

mCameraHelper.registerUSB();

}

}

private void initButtons()

{

btnPhoto=(Button)findViewById(R.id.btn_TakePhoto);

btnPhoto.setOnClickListener(new View.OnClickListener() {

@Override

            public void onClick(View view) {

if (mCameraHelper ==null || !mCameraHelper.isCameraOpened()) {

showShortMsg("sorry,camera open failed");

return;

}

String picPath ="/sdcard/iScopePro/" +"image/"+ System.currentTimeMillis()

+ UVCCameraHelper.SUFFIX_JPEG;

Log.e("AmosDemo","save picPath picPath:" + picPath);

mCameraHelper.capturePicture(picPath,new AbstractUVCCameraHandler.OnCaptureListener() {

@Override

                    public void onCaptureResult(String path) {

Log.e("AmosDemo","save path:" + path);

}

});

}

});

btnStartRec=(Button)findViewById(R.id.btn_Rec_Start);

btnStartRec.setOnClickListener(new View.OnClickListener() {

@Override

            public void onClick(View view) {

if (mCameraHelper ==null || !mCameraHelper.isCameraOpened()) {

showShortMsg("sorry,camera open failed");

return;

}

if (!mCameraHelper.isPushing()) {

String videoPath ="/sdcard/iScopePro/" +"image/" + System.currentTimeMillis();

FileUtils.createfile(FileUtils.ROOT_PATH +"test666.h264");

// if you want to record,please create RecordParams like this

                    RecordParams params =new RecordParams();

params.setRecordPath(videoPath);

params.setRecordDuration(0);// 设置为0,不分割保存

// params.setVoiceClose(mSwitchVoice.isChecked());    // is close voice

                    params.setVoiceClose(true);

mCameraHelper.startPusher(params,new AbstractUVCCameraHandler.OnEncodeResultListener() {

@Override

                        public void onEncodeResult(byte[] data,int offset,int length,long timestamp,int type) {

// type = 1,h264 video stream

                            if (type ==1) {

FileUtils.putFileStream(data, offset, length);

}

// type = 0,aac audio stream

                            if (type ==0) {

}

}

@Override

                        public void onRecordResult(String videoPath) {

Log.e("AmosDemo","videoPath = " + videoPath);

}

});

showShortMsg("start record...");

}

}

});

btnStopRec=(Button)findViewById(R.id.btn_Rec_Stop);

btnStopRec.setOnClickListener(new View.OnClickListener() {

@Override

            public void onClick(View view) {

FileUtils.releaseFile();

mCameraHelper.stopPusher();

showShortMsg("stop record...");

}

});

btnRotate=(Button)findViewById(R.id.btn_Rotate);

btnRotate.setOnClickListener(new View.OnClickListener() {

@Override

            public void onClick(View view) {

}

});

}

@Override

    public USBMonitor getUSBMonitor() {

return mCameraHelper.getUSBMonitor();

}

@Override

    public void onDialogResult(boolean canceled) {

if (canceled) {

showShortMsg("取消操作");

}

}

public boolean isCameraOpened() {

return mCameraHelper.isCameraOpened();

}

@Override

    public void onSurfaceCreated(CameraViewInterface view, Surface surface) {

if (!isPreview &&mCameraHelper.isCameraOpened()) {

mCameraHelper.startPreview(mUVCCameraView);

isPreview =true;

}

}

@Override

    public void onSurfaceChanged(CameraViewInterface view, Surface surface,int width,int height) {

}

@Override

    public void onSurfaceDestroy(CameraViewInterface view, Surface surface) {

if (isPreview &&mCameraHelper.isCameraOpened()) {

mCameraHelper.stopPreview();

isPreview =false;

}

}

}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,591评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,448评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,823评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,204评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,228评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,190评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,078评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,923评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,334评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,550评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,727评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,428评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,022评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,672评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,826评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,734评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,619评论 2 354

推荐阅读更多精彩内容