Bez popisu

ceshi.html 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <html>
  2. <head>
  3. <meta charset="UTF-8">
  4. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  5. <title>getUserMedia test</title>
  6. </head>
  7. <body>
  8. <button onclick="shotCut()">切换摄像头</button>
  9. <video id="video" autoplay="true" playsinline></video>
  10. <script>
  11. var video = document.querySelector("#video");
  12. var front = false;
  13. var nativeStream
  14. var videoInputDevices = []
  15. JSON.stringify()
  16. if((navigator.mediaDevices && navigator.mediaDevices.getUserMedia)) {
  17. navigator.mediaDevices.getUserMedia({
  18. // video: { facingMode: "user" },
  19. video: { facingMode: "environment" },
  20. audio: false
  21. })
  22. .then(function(stream) {
  23. mediumInfo()
  24. video.srcObject = stream;
  25. nativeStream = stream
  26. video.play();
  27. })
  28. .catch(function(err) {
  29. console.log("你拒绝使用相机:" + err);
  30. });
  31. } else {
  32. console.log("您的浏览器不支持影像功能");
  33. }
  34. //获取摄像头,音频设备信息
  35. function mediumInfo() {
  36. navigator.mediaDevices.enumerateDevices()
  37. .then(gotDevices).catch(handleError);
  38. function gotDevices(deviceInfos) {
  39. deviceInfos.forEach(function(n) {
  40. if(n.kind === 'videoinput') {
  41. videoInputDevices.push(n);
  42. }
  43. })
  44. alert(JSON.stringify(videoInputDevices))
  45. }
  46. function handleError(error) {
  47. //alert(JSON.stringify(error));
  48. }
  49. }
  50. //切换摄像头
  51. function shotCut() {
  52. front = !front
  53. //关闭本地媒体流
  54. if(nativeStream) {
  55. nativeStream.getVideoTracks()[0].stop();
  56. }
  57. navigator.mediaDevices.getUserMedia({
  58. audio: false, //这里是为了摄像头切换时,回显本地媒体,禁止本地声音
  59. video: { facingMode: (front? "user" : "environment") }
  60. }).then((stream) => {
  61. //本地摄像头切换
  62. nativeStream = stream
  63. video.srcObject = nativeStream;
  64. //微信端浏览器适配,需要先stop,然后执行这个函数
  65. video.onloadedmetadata = function() { //媒体流直接关闭掉后这里会重新执行
  66. if(nativeStream.active) { //在这里需要做判断,判断媒体流处于活动状态
  67. video.play();
  68. }
  69. }
  70. }).catch((res) => {
  71. alert('getUserMedia() error1: ' + res.name);
  72. })
  73. // try {
  74. //
  75. //
  76. // } catch(e) {
  77. // alert(JSON.stringify(e));
  78. // }
  79. }
  80. </script>
  81. </body>
  82. </html>