当前位置:   article > 正文

HTML5调用摄像头录制视频_stoprecordcallback

stoprecordcallback

HTML5调用摄像头录制视频
不支持ie,ie下不支持webrtc,无法使用navigator.getUserMedia调用摄像头

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>video recoder</title>
  5. <script src="fileSaver.js"></script>
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  7. <meta charset="utf-8">
  8. <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
  9. <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  10. </head>
  11. <style>
  12. body{
  13. background-color:#EFEDEF;
  14. }
  15. </style>
  16. <body>
  17. <article style="border:1px solid white;width:400px;height:400px;margin:0 auto;background-color:white;">
  18. <section class="experiment" style="width:320px; height:240px;border:1px solid green; margin:50px auto;">
  19. <div id="videos-container" style="width:320px; height:240px;">
  20. </div>
  21. </section>
  22. <section class="experiment" style="text-align:center;border:none; margin-top:20px;">
  23. <button id="openCamera">打开摄像头</button>
  24. <button id="start-recording" disabled>开始录制</button>
  25. <button id="save-recording" disabled>保存</button>
  26. <!--<a href="javascript:void(0)" onclick="send()">发送</a>-->
  27. </section>
  28. </article>
  29. <script>
  30. var mediaStream;
  31. var recorderFile;
  32. var stopRecordCallback;
  33. var openBtn = document.getElementById("openCamera");
  34. var startBtn = document.getElementById("start-recording");
  35. var saveBtn = document.getElementById("save-recording");
  36. openBtn.onclick = function() {
  37. this.disabled = true;
  38. startBtn.disabled=false;
  39. openCamera();
  40. };
  41. startBtn.onclick = function() {
  42. this.disabled = true;
  43. startRecord();
  44. };
  45. saveBtn.onclick = function() {
  46. saver();
  47. // alert('Drop WebM file on Chrome or Firefox. Both can play entire file. VLC player or other players may not work.');
  48. };
  49. var mediaRecorder;
  50. var videosContainer = document.getElementById('videos-container');
  51. function openCamera(){
  52. var len = videosContainer.childNodes.length;
  53. for(var i=0;i<len;i++){
  54. videosContainer.removeChild(videosContainer.childNodes[i]);
  55. }
  56. var video = document.createElement('video');
  57. var videoWidth = 320;
  58. var videoHeight = 240;
  59. video.controls = false;
  60. video.muted = true;
  61. video.width = videoWidth;
  62. video.height = videoHeight;
  63. MediaUtils.getUserMedia(true, false, function (err, stream) {
  64. if (err) {
  65. throw err;
  66. } else {
  67. // 通过 MediaRecorder 记录获取到的媒体流
  68. console.log();
  69. mediaRecorder = new MediaRecorder(stream);
  70. mediaStream = stream;
  71. var chunks = [], startTime = 0;
  72. video.srcObject = stream;
  73. video.play();
  74. videosContainer.appendChild(video);
  75. mediaRecorder.ondataavailable = function(e) {
  76. mediaRecorder.blobs.push(e.data);
  77. chunks.push(e.data);
  78. };
  79. mediaRecorder.blobs = [];
  80. mediaRecorder.onstop = function (e) {
  81. recorderFile = new Blob(chunks, { 'type' : mediaRecorder.mimeType });
  82. chunks = [];
  83. if (null != stopRecordCallback) {
  84. stopRecordCallback();
  85. }
  86. };
  87. }
  88. });
  89. }
  90. // 停止录制
  91. function stopRecord(callback) {
  92. stopRecordCallback = callback;
  93. // 终止录制器
  94. mediaRecorder.stop();
  95. // 关闭媒体流
  96. MediaUtils.closeStream(mediaStream);
  97. }
  98. var MediaUtils = {
  99. /**
  100. * 获取用户媒体设备(处理兼容的问题)
  101. * @param videoEnable {boolean} - 是否启用摄像头
  102. * @param audioEnable {boolean} - 是否启用麦克风
  103. * @param callback {Function} - 处理回调
  104. */
  105. getUserMedia: function (videoEnable, audioEnable, callback) {
  106. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia
  107. || navigator.msGetUserMedia || window.getUserMedia;
  108. var constraints = {video: videoEnable, audio: audioEnable};
  109. if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
  110. navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
  111. callback(false, stream);
  112. })['catch'](function(err) {
  113. callback(err);
  114. });
  115. } else if (navigator.getUserMedia) {
  116. navigator.getUserMedia(constraints, function (stream) {
  117. callback(false, stream);
  118. }, function (err) {
  119. callback(err);
  120. });
  121. } else {
  122. callback(new Error('Not support userMedia'));
  123. }
  124. },
  125. /**
  126. * 关闭媒体流
  127. * @param stream {MediaStream} - 需要关闭的流
  128. */
  129. closeStream: function (stream) {
  130. if (typeof stream.stop === 'function') {
  131. stream.stop();
  132. }
  133. else {
  134. let trackList = [stream.getAudioTracks(), stream.getVideoTracks()];
  135. for (let i = 0; i < trackList.length; i++) {
  136. let tracks = trackList[i];
  137. if (tracks && tracks.length > 0) {
  138. for (let j = 0; j < tracks.length; j++) {
  139. let track = tracks[j];
  140. if (typeof track.stop === 'function') {
  141. track.stop();
  142. }
  143. }
  144. }
  145. }
  146. }
  147. }
  148. };
  149. function startRecord() {
  150. mediaRecorder.start();
  151. setTimeout(function(){
  152. // 结束
  153. stopRecord(function() {
  154. alert("录制成功!");
  155. openBtn.disabled=false;
  156. saveBtn.disabled=false;
  157. //send();
  158. });
  159. }, 5000);
  160. }
  161. function saver(){
  162. var file = new File([recorderFile], 'msr-' + (new Date).toISOString().replace(/:|\./g, '-') + '.mp4', {
  163. type: 'video/mp4'
  164. });
  165. saveAs(file);
  166. }
  167. function send(){
  168. var file = new File([recorderFile], 'msr-' + (new Date).toISOString().replace(/:|\./g, '-') + '.mp4', {
  169. type: 'video/mp4'
  170. });
  171. var data = new FormData();
  172. data.append("username", "test");
  173. data.append("userfile", file);
  174. var req = new XMLHttpRequest();
  175. req.open("POST", "com.spinsoft.bip.frame.utils.image.saveMp4.biz.ext");
  176. req.send(data);
  177. }
  178. </script>
  179. </body>
  180. </html>

fileSaver.js

  1. /* FileSaver.js
  2. * A saveAs() FileSaver implementation.
  3. * 1.3.2
  4. * 2016-06-16 18:25:19
  5. *
  6. * By Eli Grey, http://eligrey.com
  7. * License: MIT
  8. * See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
  9. */
  10. /*global self */
  11. /*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */
  12. /*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
  13. var saveAs = saveAs || (function(view) {
  14. "use strict";
  15. // IE <10 is explicitly unsupported
  16. if (typeof view === "undefined" || typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) {
  17. return;
  18. }
  19. var
  20. doc = view.document
  21. // only get URL when necessary in case Blob.js hasn't overridden it yet
  22. , get_URL = function() {
  23. return view.URL || view.webkitURL || view;
  24. }
  25. , save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a")
  26. , can_use_save_link = "download" in save_link
  27. , click = function(node) {
  28. var event = new MouseEvent("click");
  29. node.dispatchEvent(event);
  30. }
  31. , is_safari = /constructor/i.test(view.HTMLElement) || view.safari
  32. , is_chrome_ios =/CriOS\/[\d]+/.test(navigator.userAgent)
  33. , throw_outside = function(ex) {
  34. (view.setImmediate || view.setTimeout)(function() {
  35. throw ex;
  36. }, 0);
  37. }
  38. , force_saveable_type = "application/octet-stream"
  39. // the Blob API is fundamentally broken as there is no "downloadfinished" event to subscribe to
  40. , arbitrary_revoke_timeout = 1000 * 40 // in ms
  41. , revoke = function(file) {
  42. var revoker = function() {
  43. if (typeof file === "string") { // file is an object URL
  44. get_URL().revokeObjectURL(file);
  45. } else { // file is a File
  46. file.remove();
  47. }
  48. };
  49. setTimeout(revoker, arbitrary_revoke_timeout);
  50. }
  51. , dispatch = function(filesaver, event_types, event) {
  52. event_types = [].concat(event_types);
  53. var i = event_types.length;
  54. while (i--) {
  55. var listener = filesaver["on" + event_types[i]];
  56. if (typeof listener === "function") {
  57. try {
  58. listener.call(filesaver, event || filesaver);
  59. } catch (ex) {
  60. throw_outside(ex);
  61. }
  62. }
  63. }
  64. }
  65. , auto_bom = function(blob) {
  66. // prepend BOM for UTF-8 XML and text/* types (including HTML)
  67. // note: your browser will automatically convert UTF-16 U+FEFF to EF BB BF
  68. if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
  69. return new Blob([String.fromCharCode(0xFEFF), blob], {type: blob.type});
  70. }
  71. return blob;
  72. }
  73. , FileSaver = function(blob, name, no_auto_bom) {
  74. if (!no_auto_bom) {
  75. blob = auto_bom(blob);
  76. }
  77. // First try a.download, then web filesystem, then object URLs
  78. var
  79. filesaver = this
  80. , type = blob.type
  81. , force = type === force_saveable_type
  82. , object_url
  83. , dispatch_all = function() {
  84. dispatch(filesaver, "writestart progress write writeend".split(" "));
  85. }
  86. // on any filesys errors revert to saving with object URLs
  87. , fs_error = function() {
  88. if ((is_chrome_ios || (force && is_safari)) && view.FileReader) {
  89. // Safari doesn't allow downloading of blob urls
  90. var reader = new FileReader();
  91. reader.onloadend = function() {
  92. var url = is_chrome_ios ? reader.result : reader.result.replace(/^data:[^;]*;/, 'data:attachment/file;');
  93. var popup = view.open(url, '_blank');
  94. if(!popup) view.location.href = url;
  95. url=undefined; // release reference before dispatching
  96. filesaver.readyState = filesaver.DONE;
  97. dispatch_all();
  98. };
  99. reader.readAsDataURL(blob);
  100. filesaver.readyState = filesaver.INIT;
  101. return;
  102. }
  103. // don't create more object URLs than needed
  104. if (!object_url) {
  105. object_url = get_URL().createObjectURL(blob);
  106. }
  107. if (force) {
  108. view.location.href = object_url;
  109. } else {
  110. var opened = view.open(object_url, "_blank");
  111. if (!opened) {
  112. // Apple does not allow window.open, see https://developer.apple.com/library/safari/documentation/Tools/Conceptual/SafariExtensionGuide/WorkingwithWindowsandTabs/WorkingwithWindowsandTabs.html
  113. view.location.href = object_url;
  114. }
  115. }
  116. filesaver.readyState = filesaver.DONE;
  117. dispatch_all();
  118. revoke(object_url);
  119. }
  120. ;
  121. filesaver.readyState = filesaver.INIT;
  122. if (can_use_save_link) {
  123. object_url = get_URL().createObjectURL(blob);
  124. setTimeout(function() {
  125. save_link.href = object_url;
  126. save_link.download = name;
  127. click(save_link);
  128. dispatch_all();
  129. revoke(object_url);
  130. filesaver.readyState = filesaver.DONE;
  131. });
  132. return;
  133. }
  134. fs_error();
  135. }
  136. , FS_proto = FileSaver.prototype
  137. , saveAs = function(blob, name, no_auto_bom) {
  138. return new FileSaver(blob, name || blob.name || "download", no_auto_bom);
  139. }
  140. ;
  141. // IE 10+ (native saveAs)
  142. if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) {
  143. return function(blob, name, no_auto_bom) {
  144. name = name || blob.name || "download";
  145. if (!no_auto_bom) {
  146. blob = auto_bom(blob);
  147. }
  148. return navigator.msSaveOrOpenBlob(blob, name);
  149. };
  150. }
  151. FS_proto.abort = function(){};
  152. FS_proto.readyState = FS_proto.INIT = 0;
  153. FS_proto.WRITING = 1;
  154. FS_proto.DONE = 2;
  155. FS_proto.error =
  156. FS_proto.onwritestart =
  157. FS_proto.onprogress =
  158. FS_proto.onwrite =
  159. FS_proto.onabort =
  160. FS_proto.onerror =
  161. FS_proto.onwriteend =
  162. null;
  163. return saveAs;
  164. }(
  165. typeof self !== "undefined" && self
  166. || typeof window !== "undefined" && window
  167. || this.content
  168. ));
  169. // `self` is undefined in Firefox for Android content script context
  170. // while `this` is nsIContentFrameMessageManager
  171. // with an attribute `content` that corresponds to the window
  172. if (typeof module !== "undefined" && module.exports) {
  173. module.exports.saveAs = saveAs;
  174. } else if ((typeof define !== "undefined" && define !== null) && (define.amd !== null)) {
  175. define("FileSaver.js", function() {
  176. return saveAs;
  177. });
  178. }

转载于:https://blog.csdn.net/mrzhangdulin/article/details/84560146 

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
  

闽ICP备14008679号