原网址:http://www.haolizi.net/example/view_3075.html#download



【核心代码】

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 public class VideoChat extends Base implements SurfaceHolder.Callback, Camera.PreviewCallback,OnBitmapLoaded{            private SurfaceHolder surfaceHolder;      private SurfaceView surfaceView;      private Camera camera;            private VideoView myView;            private String chatterIP; //记录当前用户ip      //线程池,用来发送图片数据      private ExecutorService executors=Executors.newFixedThreadPool(TCPVideoReceiveListener.THREAD_COUNT);             final int REFRESH= 0 ;                     private int port=Constant.VIDEO_PORT;              private TCPVideoReceiveListener videoReceiveListener;       private UDPVoiceListener voiceListener;              private boolean stop; //标识activity被遮挡             private Handler handler= new Handler(){          public void handleMessage(android.os.Message msg) {              myView.setBitmap((Bitmap)msg.obj);          };      };            @Override      protected void onCreate(Bundle savedInstanceState) {          super .onCreate(savedInstanceState);          setContentView(R.layout.video_chat1);          findViews();          chatterIP=getIntent().getStringExtra( "IP" );          try {              voiceListener=UDPVoiceListener.getInstance(InetAddress.getByName(chatterIP));               voiceListener.open();          } catch (Exception e) {              e.printStackTrace();              showToast( "抱歉,语音聊天器打开失败" );              try {                  voiceListener.close();              } catch (IOException e1) {                  e1.printStackTrace();              }          }                               new Thread( new Runnable() {              @Override              public void run() {                  try {                      videoReceiveListener=TCPVideoReceiveListener.getInstance();                      videoReceiveListener.setBitmapLoaded(VideoChat. this );                      if (!videoReceiveListener.isRunning())                          videoReceiveListener.open(); //先监听端口,然后连接                  } catch (IOException e1) {                      e1.printStackTrace();                      runOnUiThread( new Runnable() {                          @Override                          public void run() {                              showToast( "非常抱歉,视屏连接失败" );                              finish();                          }                      });                  }                            }          }).start();           SpotManager.getInstance( this ).showSpotAds( this );      }            private void findViews(){          surfaceView=(SurfaceView) findViewById(R.id.video_chat_preview);          surfaceHolder=surfaceView.getHolder();          surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);          surfaceHolder.addCallback( this );          myView=(VideoView) findViewById(R.id.video_chat_myview);          TextView topTitle=(TextView) findViewById(R.id.toptextView);          topTitle.setText(getIntent().getStringExtra( "name" ));      }            @Override      protected void onPause() {          stop= true ;          super .onPause();      }        @Override      public void onPreviewFrame( final byte [] data, final Camera camera) {          executors.execute( new Runnable() {              @Override              public void run() {                  try {                      Socket socket= new Socket(InetAddress.getByName(chatterIP), port);                      OutputStream out=socket.getOutputStream();                                           YuvImage image = new YuvImage(data, PreviewFormat, w, h, null );                     ByteArrayOutputStream os = new ByteArrayOutputStream();                     Rect rect= new Rect( 0 , 0 , w, h);                     //1:将YUV数据格式转化成jpeg                     if (!image.compressToJpeg(rect, 100 , os))  return ;                                          //2:将得到的字节数组压缩成bitmap                      Bitmap bmp = Util.decodeVideoBitmap(os.toByteArray(), 200 ); //                  Bitmap bmp = Util.decodeSampledBitmapFromFile(os.toByteArray(), 200, 200); //                 Bitmap bmp=BitmapFactory.decodeByteArray(data, offset, length, opts)                      Matrix matrix= new Matrix();                      matrix.setRotate(- 90 ); //                  matrix.postScale(2.0f, 2.0f);                      //3:旋转90                      bmp=Bitmap.createBitmap(bmp, 0 , 0 , bmp.getWidth(), bmp.getHeight(), matrix, true );                      //4:将最后的bitmap转化为字节流发送                      ByteArrayOutputStream baos = new ByteArrayOutputStream();                         bmp.compress(Bitmap.CompressFormat.JPEG, 100 , baos);                        out.write(baos.toByteArray());                      out.flush();                      out.close();                      socket.close();                  catch (IOException e) {                      e.printStackTrace();                  }              }          });      }            @Override      public void onBitmapLoaded(Bitmap bitmap) {          handler.sendMessage(handler.obtainMessage(REFRESH, bitmap));          if (stop){                  try {                      //代码实现模拟用户按下back键                      String keyCommand = "input keyevent "   KeyEvent.KEYCODE_BACK;                       Runtime runtime = Runtime.getRuntime();                       runtime.exec(keyCommand);                      stop= false ;                  } catch (IOException e) {                      e.printStackTrace();                  }          }      }                        @Override      public void surfaceCreated(SurfaceHolder holder) {          int cameras=Camera.getNumberOfCameras();          CameraInfo info= new CameraInfo();          for ( int i= 0 ;i              Camera.getCameraInfo(i, info);              if (info.facing==CameraInfo.CAMERA_FACING_FRONT){                  camera=Camera.open(i);                  break ;              }          }          //没有前置摄像头          if (camera== null ) camera=Camera.open();          try {              camera.setPreviewDisplay(surfaceHolder);              camera.setPreviewCallback( this );          } catch (Exception e) {              camera.release(); //释放资源              camera= null ;          }      }                   int w ;  //宽度       int h;       int PreviewFormat;      @Override      public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {          Camera.Parameters parameters=camera.getParameters(); //得到相机设置参数          Size size = camera.getParameters().getPreviewSize(); //获取预览大小          w=size.width;          h=size.height;          parameters.setPictureFormat(PixelFormat.JPEG); //设置图片格式          PreviewFormat=parameters.getPreviewFormat();          setDisplayOrientation(camera, 90 ); //       if (Integer.parseInt(Build.VERSION.SDK) >= 8) { //            setDisplayOrientation(camera, 90); //          } else { //            if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { //              parameters.set("orientation", "portrait"); //              parameters.set("rotation", 90); //            }else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { //              parameters.set("orientation", "landscape"); //              parameters.set("rotation", 90); //            } //          }          camera.setPreviewCallback( this );          camera.setParameters(parameters);          camera.startPreview(); //开始预览      }          @Override      public void surfaceDestroyed(SurfaceHolder holder) {          if (camera!= null ){              camera.setPreviewCallback( null );              camera.stopPreview();              camera.release();              camera= null ;          }      }            protected void setDisplayOrientation(Camera camera, int angle) {          try {              Method downPolymorphic = camera.getClass().getMethod( "setDisplayOrientation" , new Class[] { int . class });              if (downPolymorphic != null )                  downPolymorphic.invoke(camera, new Object[] { angle });          } catch (Exception e1) {            e1.printStackTrace();          }        }            @Override      protected void onDestroy() {          super .onDestroy();          try {              videoReceiveListener.close();              voiceListener.close();          } catch (Exception e) {              e.printStackTrace();          }      }                  /**       * socket池,用来缓存       */      @Deprecated      class SocketPool extends Thread{          private List sockets= new LinkedList();          private final int poolSize= 30 ;          private boolean go= true ;                    @Override          public void run() {              InetAddress address = null ;              try {                  address = InetAddress.getByName(chatterIP);                  while (go){                      int count=sockets.size();                      if (count                          for ( int i= 0 ;i                              sockets.add( new Socket(address, port));                          }                      }                  }              } catch (IOException e) {                  e.printStackTrace();              }          }                    public Socket getSocket(){              if (!sockets.isEmpty()){                  Socket socket=sockets.get( 0 );                  sockets.remove( 0 );                  return socket;              }              return null ;          }                    public void close(){              go= false ;              for (Socket socket:sockets){                  try {                      socket.close();                  } catch (IOException e) {                      e.printStackTrace();                  }              }          }      } }

更多相关文章

  1. android 调用摄像头
  2. Android在SD卡上的文件读写
  3. Android(安卓)实现仿Window7图片预览窗格效果
  4. MMS PDU
  5. Android(安卓)amr语音编解码解惑
  6. Android的4种文件类型Java,class,dex,apk
  7. Android初学心得和一些资料下载
  8. Android(安卓)Studio常用设置
  9. Android初学心得和一些资料下载

随机推荐

  1. Mall 电商实战项目发布重大更新,全面支持S
  2. 不要再重复造轮子了,这款开源工具类库贼好
  3. Could not initialize derby.jdbc.Autolo
  4. Docker服务开放了这个端口,服务器分分钟变
  5. RabbitMQ实现即时通讯居然如此简单!连后端
  6. mall-swarm 微服务电商项目发布重大更新,
  7. 还在手写CRUD代码?这款开源框架助你解放双
  8. 今天开始学习C
  9. OpenYurt v0.3.0 重磅发布:全面提升边缘场
  10. 搞定Mall项目中的权限管理功能,弄懂这些问