前面,我们已经了解了怎么在android app上打开关闭和扫描,搜索wifi,现在,我来写一下怎么通过连接wifi来使app获取到IPCamera摄像头的视频。
一、通过URL获取视频的地址
二、创建输入流
三、解析图片
首先,我是通过抓包软件来抓取IPCamera摄像头的视频流,然后将其分包解析为一张一张的图片,再将其显示在界面上。由于我抓到的有GET /videostream.cgi?rate=0 HTTP/1.1 这样的字眼,所以可以知道,我所使用的是HTTP协议的摄像头。然后根据Referer: 后面的地址,可以推断出URL应为http://192.168.10.1/videostream.cgi?user=admin&pwd=&resolution=32&rate=1,主要是注意修改地址后面为/videostream.cgi,user和pwd是这个网页登入的账号和密码,就可以开始创建URL连接了。代码如下:
URL url;
url = new URL("http://192.168.10.1/videostream.cgi?user=admin&pwd=&resolution=32&rate=1"); URLConnection conn = url.openConnection(); conn.connect();
接下来,开始创建输入输出流。
InputStream input = conn.getInputStream(); BufferedInputStream in=new BufferedInputStream(input); ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
然后就可以开始分包接收到的图片了。
int readLength; String flag = "Content-Length:", flag1 = " "; while (true) { //当输入流有数据时,则创建byte数组 if (in.available() != -1) { byte buffer[] = new byte[1024]; //把读到的字节数给 readLength readLength = in.read(buffer, 0, 1024); //让readLength读满 while (readLength < 1024) { readlength = in.read(buffer, readLength - 1, 1024 - readLength); readLength = readLength + readlength; } if (readLength > 0) { strData = new String(buffer); //标记"Content-Length: "的起始位置 int index = strData.indexOf(flag); //标记" "的位置,注意是"Content-Length: "之后的第一个位置 int index1 = strData.indexOf(flag1, index); if (index1 != -1 || index1 - (index + flag.length()) > 0 || index != -1) { String len; len = strData.substring(index + flag.length(), index1); //计算本次streamLength的长度 streamLength = Integer.parseInt(len.trim()); } if (streamLength > 0) { if ((index1 + 4) < readLength) { outputStream.write(buffer, index1 + 4, readLength - index1 - 4); streamLength = streamLength - readLength + index1 + 4; } //将剩下读取的视频流存储到buffer1 byte[] buffer1 = new byte[streamLength]; int length = 0; while (length < streamLength) { if (in.available() != -1) { //Thread.sleep(50); length += in.read(buffer1, length, streamLength - length); } else{ Thread.sleep(150); } } outputStream.write(buffer1, 0, streamLength); byte[] data = outputStream.toByteArray(); BitmapFactory.Options op = new BitmapFactory.Options(); op.inSampleSize = 2; bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, op); if (bitmap != null) { //remoteSurfaceView.setImageBitmap(bitmap); handler.sendEmptyMessage(MSG_ONE); } outputStream.reset(); } } } else { Thread.sleep(300); } }
然后,通过handler来更新UI。
private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case MSG_ONE: remoteSurfaceView.setImageBitmap(bitmap); break; default: break; } } };
这样,就可以显示IPCamera的视屏画面了,但是,在我的app界面上,视频始终不能一直播放下去,总是在看到几分钟的画面之后就停下了,具体原因我还没有搞清楚,也有可能是摄像头设备的问题,希望知道的高手可以解答一下。