分享

html5 pc端录制视频 MediaStreamRecorder

 然并卵书屋 2018-09-03

自己花了一天研究出来的  html 5 录制视频并上传到服务器  这方面资料太少了  尤其是中文资料

借鉴  SegmentFault  https://segmentfault.com/q/1010000011489899

git官方      https://github.com/streamproc/MediaStreamRecorder

这俩个文档都有点坑  第一个 文档 弄出来 可以录制视频但是不能关闭摄像头  停止录制后 摄像头没有关,第二个 文档也就是 官方git 上的演示demo  可以用 但是录制后视频html5 pc端录制视频+MediaStreamRecorder

刚开始不知道怎么回事  看了文档 以为视频 设置宽度有问题   改了宽度也不行,

后来研究俩个文档  终于 再第一个文档的基础上 结合官方文档 修复停止录制视频 时摄像头不关闭的问题  ,,并且发现俩个画面的原因  官方文档  multiStreamRecorder = new MultiStreamRecorder([stream, stream]);

  想要一个画面就用这个 mediaRecorder = new MediaStreamRecorder(stream);

 

官方文档写的上传到PHP 服务器 我这里用的java后台   上传时还弄了 老半天  官方给出的 

 

 

XMLHttpRequest 上传 之前没见过这玩意 弄了半天也不行 直接改成ajax 上传了

停止视频用    mediaRecorder.stop(); 的话 就会出现 不关闭摄像头的问题

     后才用官方给的      mediaRecorder.stop(); mediaRecorder.stream.stop(); 但是我实际发现 用一个mediaRecorder.stream.stop(); 就够了

html5 pc端录制视频+MediaStreamRecorder

html5 pc端录制视频+MediaStreamRecorder

我把代码贴出来, 

 

1'100%' height='480' id='myVideo'>
2 
3
4 
5'videolz()' type='button'  class='btn btn-danger' style='width: 100%; font-size: 32px'>'glyphicon glyphicon-facetime-video' aria-hidden='true' id='videostr'>视频描述
001//  判断浏览器
002var root ='<%=basePath %>';
003var aa = '' ; //防止两次上传
004var mediaRecorder ;
005var index=1;//定时加1         
006var dingshi;
007var mediaConstraints = { audio: true, video: { width: 1280, height: 720 } };
008 
009function captureUserMedia(mediaConstraints, successCallback, errorCallback) {
010    navigator.mediaDevices.getUserMedia(mediaConstraints).then(successCallback).catch(errorCallback);
011}
012function onMediaError(e) {
013    
014}
015function onMediaSuccess(stream) {
016     var video = document.querySelector('video');
017          //  赋值 video 并开始播放
018          video.srcObject = stream;
019          video.onloadedmetadata = function(e) {
020            video.play();
021          };
022          mediaRecorder = new MediaStreamRecorder(stream);
023          mediaRecorder.stream = stream;
024         /*    //  录像api的调用 */
025                mediaRecorder.mimeType = 'video/mp4';
026              dingshi = window.setInterval(function(){
027                $('#videostr').html('保存视频'+index+'秒');
028                index++;
029            }
030            ,1000); 
031              
032            mediaRecorder.start(12000000000);
033            //  停止录像以后的回调函数
034           
035            mediaRecorder.ondataavailable = function (blob) {
036                if(aa == ''){
037                     var file = new File([blob], 'msr-' + (new Date).toISOString().replace(/:|\./g, '-') + '.mp4', {
038                         type: 'video/mp4'
039                     });
040                     var formData = new FormData();
041                     formData.append('file', file);
042                     console.log(formData);
043 
044                    $.ajax({
045                        url :  root+'/upload/video.do',
046                        type : 'post',
047                        cache : false,
048                        data: formData,
049                        dataType : 'json',
050                        processData: false,
051                        contentType: false,
052                        error : function() {
053                            alert('暂时无法操作,请刷新后再试!');
054                        },
055                        success : function(result) {
056                             
057                            if (result.code == 0) {
058                                var params = result.data;
059                                console.log(params);
060                                console.log(params.fileUrl);
061                                /* $('#lzvideo').attr('src', params.fileUrl); */
062                                 
063                            } else {
064                                 
065                            }
066                        }
067                    });
068                     
069                aa = blob;
070                }
071            };
072}
073 
074           function videolz(){
075                if( $('#videostr').text()=='视频描述'){
076                $('#videostr').html('保存视频');
077                $('#videostr').removeClass('glyphicon-facetime-video');
078                $('#videostr').addClass('glyphicon-pause')
079                /* $('#videos').append('') */
080                 //  开始录像
081                 $('#myVideo').show();
082                captureUserMedia(mediaConstraints, onMediaSuccess, onMediaError);
083 
084                }else{
085                $('#videostr').html('视频描述');
086                $('#videostr').addClass('glyphicon-facetime-video');
087                $('#videostr').removeClass('glyphicon-pause')
088                /*  $('#myVideo').remove();  */
089           //  停止录像
090                 /*  mediaRecorder.stop(); */
091              mediaRecorder.stream.stop();
092                /*  $('#myVideo').unbind(); */
093               
094                index=1;
095                window.clearInterval(dingshi);
096                }
097        
098            }
099             
100 
101 
102
01/*
02 * 上传视频
03 */
04@RequestMapping(value='video')
05@ResponseBody
06public Result uoloadVideo(@RequestParam('file') MultipartFile file,Model model,HttpServletRequest request, HttpServletResponse response) {
07 
08    Result result = new Result();
09    Map data = new HashMap();
10    String serverPath = '/upload/' + new SimpleDateFormat('yyyyMM').format(new Date()) + '/';
11    String basePath = request.getScheme()+'://'+request.getServerName()+':'+request.getServerPort();
12    String filePath = request.getSession().getServletContext().getRealPath(serverPath);
13    String fileName = UUID.randomUUID().toString().replaceAll('-', '') + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'));
14    String fileUrl = request.getContextPath() + serverPath + fileName;
15 
16    File targetFile = new File(filePath, fileName);
17    if (!targetFile.exists()) {
18        targetFile.mkdirs();
19    }
20 
21    try {
22        file.transferTo(targetFile);
23        System.out.println(basePath);
24        data.put('fileUrl', basePath+fileUrl);
25        result = new Result(0, '上传成功', data);
26    } catch (Exception e) {
27        result = new Result(1, '上传异常');
28    }
29 
30    return result;
31 
32}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多