camera.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. class ImCamera {
  2. constructor() {
  3. this.stream = null;
  4. }
  5. }
  6. ImCamera.prototype.isEnable = function () {
  7. return !!navigator && !!navigator.mediaDevices && !!navigator.mediaDevices.getUserMedia;
  8. }
  9. ImCamera.prototype.openVideo = function () {
  10. return new Promise((resolve, reject) => {
  11. if (this.stream) {
  12. this.close()
  13. }
  14. let constraints = {
  15. video: true,
  16. audio: {
  17. echoCancellation: true, //音频开启回音消除
  18. noiseSuppression: true // 开启降噪
  19. }
  20. }
  21. navigator.mediaDevices.getUserMedia(constraints).then((stream) => {
  22. console.log("摄像头打开")
  23. this.stream = stream;
  24. resolve(stream);
  25. }).catch((e) => {
  26. console.log(e)
  27. console.log("摄像头未能正常打开")
  28. reject({
  29. code: 0,
  30. message: "摄像头未能正常打开"
  31. })
  32. })
  33. })
  34. }
  35. ImCamera.prototype.openAudio = function () {
  36. return new Promise((resolve, reject) => {
  37. let constraints = {
  38. video: false,
  39. audio: {
  40. echoCancellation: true, //音频开启回音消除
  41. noiseSuppression: true // 开启降噪
  42. }
  43. }
  44. navigator.mediaDevices.getUserMedia(constraints).then((stream) => {
  45. this.stream = stream;
  46. resolve(stream);
  47. }).catch(() => {
  48. console.log("麦克风未能正常打开")
  49. reject({
  50. code: 0,
  51. message: "麦克风未能正常打开"
  52. })
  53. })
  54. })
  55. }
  56. ImCamera.prototype.close = function () {
  57. // 停止流
  58. if (this.stream) {
  59. this.stream.getTracks().forEach((track) => {
  60. track.stop();
  61. });
  62. }
  63. }
  64. export default ImCamera;