在好例子网,分享、交流、成长!
您当前所在位置:首页Java 开发实例Android平台开发 → Android 录制 H264视频并上传至服务器 例子源码下载

Android 录制 H264视频并上传至服务器 例子源码下载

Android平台开发

下载此实例
  • 开发语言:Java
  • 实例大小:0.10M
  • 下载次数:83
  • 浏览次数:1744
  • 发布时间:2013-08-16
  • 实例类别:Android平台开发
  • 发 布 人:crazycode
  • 文件格式:.rar
  • 所需积分:2
 相关标签: Android 上传 视频

实例介绍

【实例简介】

android h264视频采集,通过LOCALSOCKET上传到服务器上-android video capture and playback

【实例截图】

【核心代码】


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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
package com.android.getH264FormMediaRecorder;
 
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
 
import java.net.Socket;
 
import java.net.UnknownHostException;
import java.security.InvalidParameterException;
 
 
 
import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
 
 
 
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.LocalServerSocket;
import android.net.LocalSocket;
import android.net.LocalSocketAddress;
import android.os.Bundle;
import android.os.Process;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.SurfaceHolder.Callback;
import android.widget.Toast;
 
public class VideoCameraActivity extends Activity implements Callback, Runnable {
     
     
     
    private String ip=null;
    private SurfaceHolder mSurfaceHolder;
    private boolean mMediaRecorderRecording = false;
    private static Camera m_camera=null;
     
    private CameraStreamer streamer = null;
    private MediaPlayer mMediaPlayer=null;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       // setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);  
         
        InitSurfaceView();
        InitMediaSharePreference();
        streamer =new CameraStreamer();
 
 
 
 
    }
 
    private PictureCallback jpegCallback = new PictureCallback() {
        public void onPictureTaken(byte[] _data, Camera _camera) {
            // TODO Handle JPEG image data
 
            /* onPictureTaken传入的第一个参数即为相片的byte */
            Bitmap bm = BitmapFactory.decodeByteArray(_data, 0, _data.length);
 
 
            File myCaptureFile = new File("/sdcard/1234566.jpg");
            try {
                BufferedOutputStream bos = new BufferedOutputStream(
                        new FileOutputStream(myCaptureFile));
 
                /* 采用压缩转档方法 */
                bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
                 
                /* 调用flush()方法,更新BufferStream */
                bos.flush();
                 
                /* 结束OutputStream */
                bos.close();
                Log.e("","file length :"  myCaptureFile.length());
                int length =(int) myCaptureFile.length();
                DataInputStream data_input= new DataInputStream(new FileInputStream(myCaptureFile));
                byte [] buffer =new byte[length];
                pic_data_output.write(intToByteArray(length));
                int read =0,temp=0;
                while(read<length)
                {
                    temp= data_input.read(buffer, read, length-read);
                    if(temp==-1)
                    {
                        Log.e("", "no data get wait for data coming.....");
                        return;
                    }
                    read  = temp;
                }
                pic_data_output.write(buffer,0, length);
                pic_data_output.flush();
                 
                /* 将拍照下来且存储完毕的图文件,显示出来 */
                // mImageView01.setImageBitmap(bm);
 
                /* 显示完图文件,立即重置相机,并关闭预览 */
                resetCamera();
                pic_data_input.close();
                pic_data_output.close();
                cap_picture_fd.close();
 
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
     
    private void resetCamera()
    {
          
      if (m_camera != null )
      {
          m_camera.lock();
          m_camera.stopPreview();
         
          m_camera.release();
          m_camera = null;
           
 
      }
    }
    SharedPreferences mediaPreference;
    private final String mediaShare = "media";
   
 
 
    private void InitMediaSharePreference()
    {
        mediaPreference = this.getSharedPreferences(mediaShare, Context.MODE_PRIVATE);
         
    }
     
       
     LocalServerSocket lss =null;
     LocalSocket receiver=null;
     LocalSocket sender=null;
 
    private void InitLocalSocket(){
        try {
            lss = new LocalServerSocket ("h264");
            receiver = new LocalSocket ();
             
            receiver.connect(new LocalSocketAddress("h264"));
            receiver.setReceiveBufferSize(500000);
            receiver.setSendBufferSize(500000);
             
            sender = lss.accept();
            sender.setReceiveBufferSize(500000);
            sender.setSendBufferSize(500000);
        } catch (IOException e) {
            e.printStackTrace();
            this.finish();
            return;
        }
    }
  
    LocalServerSocket lss2 =null;
    LocalSocket receiver2=null;
    LocalSocket sender2=null;
 
     
    private SurfaceView mSurfaceView;
    private void InitSurfaceView()
    {
        mSurfaceView = (SurfaceView)this.findViewById(R.id.surface_camera);
        SurfaceHolder holder = mSurfaceView.getHolder();
        holder.addCallback(this);
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
         
    }
     
 
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height)
    {
        mSurfaceHolder  = holder;
        if(!mMediaRecorderRecording)
        {
            InitLocalSocket();
            getSPSAndPPS();
            if (!initializeVideo()) {
              return;  
            }
            startVideoRecording();
        }
    }
     
    //get sps and pps if have record
    private void getSPSAndPPS(){
        StartMdatPlace = mediaPreference.getInt(
                String.format("mdata_%d%d.mdat", videoWidth,videoHeight),
                -1);
        if(StartMdatPlace!=-1)
        {
            byte[] temp = new byte[100];
            try {
                FileInputStream file_in = VideoCameraActivity.this.openFileInput(
                        String.format("%d%d.sps", videoWidth,videoHeight));
                 
                int index = 0;
                int read=0;
                while(true)
                {
                    read = file_in.read(temp,index,10);
                    if(read==-1) break;
                    else index  = read;
                }
                Log.e("", "sps length:" index);
                SPS = new byte[index];
                System.arraycopy(temp, 0, SPS, 0, index);
                                
                file_in.close();
                 
                index =0;
                //read PPS
                file_in = VideoCameraActivity.this.openFileInput(
                        String.format("%d%d.pps", videoWidth,videoHeight));
                while(true)
                {
                    read = file_in.read(temp,index,10);
                    if(read==-1) break;
                    else index =read;
                }
                Log.e("", "pps length:" index);
                PPS = new byte[index];
                System.arraycopy(temp, 0, PPS, 0, index);
                 
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else
        {
            SPS = null;
            PPS = null;
        }
    }
     
     
    public void surfaceCreated(SurfaceHolder holder)
    {
        mSurfaceHolder = holder;
    }
     
    public void surfaceDestroyed(SurfaceHolder holder)
    {
        releaseMediaRecorder();
        if (data_output!=null) {
            try {
                data_output.close();
                data_output=null;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (client_fd != null) {
            try {
                client_fd.close();
                client_fd=null;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
     
    private static MediaRecorder  mMediaRecorder = null;
    private int videoWidth = 320;
    private int videoHeight = 240;
    private int videoRate = 15;
 
 
    private String fd = "data/data/com.android.getH264FormMediaRecorder/h264.3gp";
     
    private boolean initializeVideo(){
        if(mSurfaceHolder==null)
            return false;
         
//      TODO:get supported width and height
         
        if (!init_streaming_socket()) {
            return false;
        }
        mMediaRecorderRecording = true;
        if(mMediaRecorder == null)
            mMediaRecorder = new MediaRecorder ();
        else
            mMediaRecorder.reset();
 
        try
        {
            m_camera = Camera.open();
        } catch (RuntimeException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        m_camera.setDisplayOrientation(90);
 
        m_camera.unlock();
 
        mMediaRecorder.setCamera(m_camera);
        mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mMediaRecorder.setVideoEncodingBitRate(1000);
        mMediaRecorder.setVideoFrameRate(videoRate);
        mMediaRecorder.setVideoSize(videoWidth, videoHeight);
        mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
        mMediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());
 
     
        mMediaRecorder.setMaxDuration(0);
        mMediaRecorder.setMaxFileSize(0);
        if(SPS==null)
        {
            mMediaRecorder.setOutputFile(fd);
        }
        else
        {
            mMediaRecorder.setOutputFile(sender.getFileDescriptor());
        }
         
         
        try {
            mMediaRecorder.prepare();
            mMediaRecorder.start();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            releaseMediaRecorder();
        }
 
     
        return true;
    }
     
     
    private void startVideoRecording()
    {
        new Thread (streaming).start();
         
        new Thread (picture_thread).start();
        new Thread (voice_thread).start();
        //new Thread (recv_voice_thread).start();
     
 
    }
 
    private Runnable voice_thread=new Runnable() {
         
        @Override
        public void run() {
            // TODO Auto-generated method stub
            Intent i=getIntent();
            String ip=i.getStringExtra("ip");          
            //while (mMediaRecorderRecording) {
                try {
                    streamer.setup(mSurfaceHolder,ip);
 
                } catch (Exception e) {
                    // TODO: handle exception
                    Log.e("","error");
                    return;
                }
                streamer.start();
                while (mMediaRecorderRecording)
                {
                    ;
                }
                //streamer.stop();
            //}
        }
    };
     
    private Runnable streaming = new Runnable()
    {
        public void run() {
            try {
                 
                if(SPS == null)
                {
                    Log.e("", "Rlease MediaRecorder and get SPS and PPS");
                    Thread.sleep(1000);
                    releaseMediaRecorder();
                     
                    //first we must get sps and pps
                    findSpsPps();
                     
                    initializeVideo();
                }
                 
                DataInputStream dataInput = new DataInputStream (receiver.getInputStream());
                 
                //skip ftyp box and mdat box(decisbe by phone)
                if(ReadSize(h264frame,StartMdatPlace,dataInput)==-1)
                {
                    return ;
                }
                 
 
                int h264head=21;
 
                 
                data_output.write(intToByteArray(h264head));
                data_output.write(head);//4
                data_output.write(SPS);//write sps  9          
                data_output.write(head);//4
                data_output.write(PPS);//write pps   4 
                data_output.flush();
                int h264length =0;
                 
                 
                while(mMediaRecorderRecording)
                {
                    h264length = dataInput.readInt();
                    byte [] oneframe =new byte [h264length];
                    if(ReadSize(oneframe,h264length,dataInput)==-1)
                    {
                        out_stream.close();
                        data_output.close();                       
                        client_fd.close();
                        return ;
                    }
                    //Log.e("", "h264length:" h264length);
 
                    int a_pix=h264length 4;
                    data_output.write(intToByteArray(a_pix));          
                    data_output.write(head);
                    data_output.write(oneframe,0,h264length);
                    data_output.flush();
 
                }
                out_stream.close();
                data_output.close();               
                client_fd.close();
                 
 
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
    private Runnable recv_voice_thread =new Runnable() {
         
        @Override
        public void run() {
            android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
            // TODO Auto-generated method stub
            while (!init_voice_socket()) {
                show_message("初始化socket错误!");
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                continue;
            }; 
             
            int iMinBufSize = AudioTrack.getMinBufferSize(8000,
                    AudioFormat.CHANNEL_CONFIGURATION_MONO,
                    AudioFormat.ENCODING_PCM_16BIT);   
            int buffer_size =16000;
            AudioTrack m_out_trk = new AudioTrack(AudioManager.STREAM_MUSIC, 8000,
                               AudioFormat.CHANNEL_CONFIGURATION_MONO,
                               AudioFormat.ENCODING_PCM_16BIT,
                               iMinBufSize,
                               AudioTrack.MODE_STREAM);
            byte []m_out_bytes=new byte[buffer_size];
           
           int bytesRead=0,byteWrite=0;
            int temp=0;
            m_out_trk.play();
            while (mMediaRecorderRecording) {
 
                while(bytesRead<buffer_size)
                {  
                try {
                    temp = data_input.read(m_out_bytes, temp, buffer_size-temp);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                bytesRead =temp;
                }
                temp=0;
                while(byteWrite < m_out_bytes.length)
                {
                    temp=m_out_trk.write(m_out_bytes, byteWrite,
                        m_out_bytes.length -byteWrite);
                    Log.e("", "h264length:" temp);
                    byteWrite  =temp;
                    if (temp<iMinBufSize)
                    {
                        break;
                    }
                }
                bytesRead=0;
                temp=0;
                byteWrite =0;
                m_out_trk.flush();
                 
             
 
                 
                 
 
            }  
            m_out_trk.stop();
            m_out_trk.release();
            m_out_trk=null;
            try {
                data_input.close();
                in_stream.close();
                voice_fd.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
             
 
        }
         
         
    };
    private Runnable picture_thread = new Runnable()
    {
        public void run()
        {
 
                while (!init_capture_socket()) {
                    show_message("初始化socket错误!");
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    continue;
                };
                int read =0,temp=0;
                byte [] pic_head =new byte[]{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
 
                 
                while(read<8)
                {
                    try {
                        temp= pic_data_input.read(pic_head, read, 8-read);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    if(temp==-1)
                    {
                        return;
                    }
                    read  = temp;
 
                }  
                mMediaRecorderRecording =true;
                releaseMediaRecorder();
 
                try
                {
                    if (sender !=null) {
                        sender.close();
                        sender =null;
                    }
                    if (receiver !=null) {
                        receiver.close();
                        receiver =null;
                    }
                     
                    if (lss !=null) {
                        lss.close();
                        lss =null;
                    }
 
 
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
                 
                mMediaRecorderRecording=false;
                streamer.stop();
                try {
                    m_camera=Camera.open();
                } catch (RuntimeException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
 
                Camera.Parameters parameters = m_camera.getParameters();
                parameters.setPictureFormat(PixelFormat.JPEG);
                parameters.setPreviewSize(320,240);
                parameters.setPictureSize(2592, 1944);
                m_camera.setParameters(parameters);
                m_camera.autoFocus(null);
                try {
                    m_camera.setPreviewDisplay(mSurfaceHolder);
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                m_camera.setDisplayOrientation(90);
                m_camera.startPreview();
                m_camera.takePicture(null, null,null, jpegCallback);
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
 
                getSPSAndPPS();
         
                InitLocalSocket();
                initializeVideo();
                startVideoRecording(); 
                return ;
 
        }
    };
 
  
     
     
    private void releaseMediaRecorder()
    {
        if(mMediaRecorder != null)
        {
            if(mMediaRecorderRecording)
            {
                mMediaRecorder.stop();
                mMediaRecorderRecording = false;
            }
            mMediaRecorder.reset();
            mMediaRecorder.release();
            mMediaRecorder = null
            m_camera.lock();
            if (m_camera!= null) {
                 
                m_camera.stopPreview();
                m_camera.release();
                 
                m_camera = null;               
            }
 
 
        }      
    }
 
    private final int MAXFRAMEBUFFER = 20480*30;//*10;//20K
    private byte[] h264frame = new byte[MAXFRAMEBUFFER];
    private final byte[] head = new byte[]{0x00,0x00,0x00,0x01};
     
     
    public void run() {
        while (true) {
             
        }
    }
     
     
 
     
     
 
     
 
    protected void onStop()
    {
        super.onStop();    
            try
            {
                if (sender !=null) {
                    sender.close();
                    sender =null;
                }
                if (receiver !=null) {
                    receiver.close();
                    receiver =null;
                }
                 
                if (lss !=null) {
                    lss.close();
                    lss =null;
                }
 
 
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
 
            mMediaRecorderRecording = false;
        finish();
        Process.killProcess(Process.myPid());
         
    }
     
     
     
     
 
    Socket client_fd=null;
    OutputStream out_stream=null;
    DataOutputStream   data_output=null;   
    private boolean init_streaming_socket()
    {
        Intent i=getIntent();
        ip=i.getStringExtra("ip");
       try {
        client_fd =new Socket(ip, 4322);
 
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
 
        e.printStackTrace();
        show_message("无法连接到服务器!");
        return false;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        show_message("无法连接到服务器!");
        return false;      
    }
    try {
        out_stream =client_fd.getOutputStream();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        show_message("无法连接到服务器!");
        return false;      
    }
 //      array_output= new ByteArrayOutputStream(20480*10);
       data_output =new DataOutputStream(out_stream);
       return true;
    }
     
     
    Socket cap_picture_fd=null;
    DataOutputStream   pic_data_output=null;  
    OutputStream pic_out_stream=null;
    InputStream  pic_in_stream=null;
    DataInputStream pic_data_input=null;
     
    private boolean init_capture_socket()  
    {
        Intent i=getIntent();
        ip=i.getStringExtra("ip");
        try {
            cap_picture_fd =new Socket(ip,8888);
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            show_message("无法连接到服务器!");
            return false;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            show_message("无法连接到服务器!");
            return false;
        }
         
        try {
            pic_out_stream =cap_picture_fd.getOutputStream();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            show_message("无法连接到服务器!");
            return false;
        }
        try {
            pic_in_stream = cap_picture_fd.getInputStream();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            show_message("无法连接到服务器!");
            return false;
        }
        pic_data_output =new DataOutputStream(pic_out_stream);
        pic_data_input =new DataInputStream(pic_in_stream);    
        return true;
 
    }
     
    private void show_message(String str)
    {
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
 
    }
 
    Socket voice_fd=null;
     
    InputStream in_stream=null;
    DataInputStream   data_input=null
    private boolean init_voice_socket()
    {
        Intent i=getIntent();
        ip=i.getStringExtra("ip");
       try {
           voice_fd =new Socket(ip, 5005);
 
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
 
        e.printStackTrace();
        show_message("无法连接到服务器!");
        return false;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        show_message("无法连接到服务器!");
        return false;      
    }
      
    try {
        in_stream =voice_fd.getInputStream();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        show_message("无法连接到服务器!");
        return false;      
    }
 //      array_output= new ByteArrayOutputStream(20480*10);
        data_input =new DataInputStream(in_stream);
       return true;
 
    }  
     
     
/////////////////////////////////////////////////////////////////////////////////////////////////  
    private byte[] SPS;
    private byte[] PPS;
    private int StartMdatPlace = 0;
     
    private void findSpsPps() throws IOException
    {
        File file = new File (fd);
        FileInputStream fileInput = new FileInputStream (file);
         
        int length = (int)file.length();
        byte[] data = new byte[length];
        fileInput.read(data);
         
        final byte[] mdat = new byte[]{0x6D,0x64,0x61,0x74};
        final byte[] avcc = new byte[]{0x61,0x76,0x63,0x43};
         
         
        //search from head
        for(int i =0 ; i<100;i  )//find StartMdatPlace
        {
            if(data[i] == mdat[0]&&data[i 1] == mdat[1] && data[i 2] == mdat[2] && data[i 3]==mdat[3])
            {
                StartMdatPlace = i 4;//find
                break;
            }
        }
        Log.e("", "StartMdatPlace:" StartMdatPlace);
        String mdatStr = String.format("mdata_%d%d.mdat",videoWidth,videoHeight);
         
         
        Editor editor = mediaPreference.edit();
        editor.putInt(mdatStr,StartMdatPlace);
        editor.commit();
         
        //search from end
        for(int i = length-1;i>0;i--)
        {
            if(data[i] == avcc[3] && data[i-1] == avcc[2] && data[i-2] == avcc[1] && data[i-3] == avcc[0])
            {
                //find avcc box
                int sps_start = i 7;
                 
                byte[] sps_3gp = new byte[2];
                sps_3gp[1] = data[sps_start];
                sps_3gp[0] = data[sps_start 1];
//              Log.e("", "0:" sps_3gp[0] "1:" sps_3gp[1]);
                 
                sps_start =2;//skip length
                 
                int sps_length = bytes2short(sps_3gp);
                Log.e("", "SPS LENGTH:" sps_length);
                 
                SPS=new byte[sps_length];
                System.arraycopy(data, sps_start, SPS, 0, sps_length);
                 
                //Save SPS
                FileOutputStream file_out = VideoCameraActivity.this.openFileOutput(
                        String.format("%d%d.sps",videoWidth,videoHeight),
                        Context.MODE_PRIVATE);
                file_out.write(SPS);
                file_out.close();
                 
                int pps_start = sps_start sps_length 1;
                byte[] pps_3gp =new byte[2];
                pps_3gp[1] = data[pps_start];
                pps_3gp[0] =data[pps_start 1];
                int pps_length = bytes2short(pps_3gp);
                Log.e("", "PPS LENGTH:" pps_length);
                 
                pps_start =2;
                 
                PPS = new byte[pps_length];
                System.arraycopy(data, pps_start, PPS,0,pps_length);
                 
                 
                //Save PPS
                file_out = VideoCameraActivity.this.openFileOutput(
                        String.format("%d%d.pps",videoWidth,videoHeight),
                        Context.MODE_PRIVATE);
                file_out.write(PPS);
                file_out.close();
                break;
            }
        }
    }
     
    public static byte[] intToByteArray(int i)
    {  
          byte[] result = new byte[4];  
          result[0] = (byte)((i >> 24) & 0xFF);
          result[1] = (byte)((i >> 16) & 0xFF);
          result[2] = (byte)((i >> 8) & 0xFF);
          result[3] = (byte)(i & 0xFF);
          return result;
           
    }
       
     
    public short bytes2short(byte[] b)
    {
        short mask = 0xff;
        short temp = 0;
        short res = 0;
        for (int i = 0; i < 2; i  )
        {
            res <<= 8;
            temp = (short) (b[1 - i] & mask);
            res |= temp;
        }
        return res;
    }
 
    private int ReadSize(byte [] oneframe,int h264length, DataInputStream dataInput)
            throws IOException, InterruptedException {
        int read = 0;
        int temp = 0;
        while (read < h264length) {
            temp = dataInput.read(oneframe, read, h264length - read);
            if (temp == -1) {
                Log.e("", "no data get wait for data coming.....");
                return -1;
            }
            read  = temp;
        }
        return 0;
    }
}


标签: Android 上传 视频

实例下载地址

Android 录制 H264视频并上传至服务器 例子源码下载

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警