camera-select.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. const video = document.getElementById('arjs-video');
  2. const button = document.getElementById('button');
  3. const select = document.getElementById('select');
  4. let currentStream;
  5. function stopMediaTracks(stream) {
  6. stream.getTracks().forEach(track => {
  7. track.stop();
  8. });
  9. }
  10. function gotDevices(mediaDevices) {
  11. select.innerHTML = '';
  12. select.appendChild(document.createElement('option'));
  13. let count = 1;
  14. mediaDevices.forEach(mediaDevice => {
  15. if (mediaDevice.kind === 'videoinput') {
  16. const option = document.createElement('option');
  17. option.value = mediaDevice.deviceId;
  18. const label = mediaDevice.label || `Camera ${count++}`;
  19. const textNode = document.createTextNode(label);
  20. option.appendChild(textNode);
  21. select.appendChild(option);
  22. }
  23. });
  24. }
  25. button.addEventListener('click', event => {
  26. if (typeof currentStream !== 'undefined') {
  27. stopMediaTracks(currentStream);
  28. }
  29. const videoConstraints = {};
  30. if (select.value === '') {
  31. videoConstraints.facingMode = 'environment';
  32. } else {
  33. videoConstraints.deviceId = { exact: select.value };
  34. }
  35. const constraints = {
  36. video: videoConstraints,
  37. audio: false
  38. };
  39. // navigator.mediaDevices
  40. // .getUserMedia(constraints)
  41. // .then(stream => {
  42. // currentStream = stream;
  43. // video.srcObject = stream;
  44. // return navigator.mediaDevices.enumerateDevices();
  45. // })
  46. // .then(gotDevices)
  47. // .catch(error => {
  48. // console.error(error);
  49. // });
  50. navigator.mediaDevices
  51. .getUserMedia(constraints)
  52. .then((stream) => {
  53. currentStream = stream;
  54. document.getElementById('arjs-video').srcObject = stream;
  55. var event = new CustomEvent("camera-init", { stream: stream });
  56. window.dispatchEvent(event);
  57. document.body.addEventListener("click", function () {
  58. document.getElementById('arjs-video').play();
  59. });
  60. return navigator.mediaDevices.enumerateDevices();
  61. })
  62. .then(gotDevices)
  63. .catch((error) => {
  64. console.error(error);
  65. });
  66. });
  67. navigator.mediaDevices.enumerateDevices().then(gotDevices);