recorder-h5.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import UNI_APP from '@/.env.js';
  2. let rc = null;
  3. let duration = 0;
  4. let chunks = [];
  5. let stream = null;
  6. let startTime = null;
  7. let checkIsEnable = () => {
  8. if (origin.indexOf('https') === -1 && origin.indexOf('localhost') === -1 &&
  9. origin.indexOf('127.0.0.1') === -1) {
  10. uni.showToast({
  11. title: '请在https环境中使用录音功能',
  12. icon: 'error'
  13. })
  14. return false;
  15. }
  16. if (!navigator.mediaDevices || !window.MediaRecorder) {
  17. uni.showToast({
  18. title: '当前浏览器不支持录音',
  19. icon: 'error'
  20. })
  21. return false;
  22. }
  23. return true;
  24. }
  25. let start = () => {
  26. return navigator.mediaDevices.getUserMedia({ audio: true }).then(audioStream => {
  27. startTime = new Date().getTime();
  28. chunks = [];
  29. stream = audioStream;
  30. rc = new MediaRecorder(stream)
  31. rc.start()
  32. })
  33. }
  34. let close = () => {
  35. stream.getTracks().forEach((track) => {
  36. track.stop()
  37. })
  38. rc.stop()
  39. }
  40. let upload = () => {
  41. return new Promise((resolve, reject) => {
  42. rc.ondataavailable = (e) => {
  43. chunks.push(e.data)
  44. }
  45. rc.onstop = () => {
  46. if(!chunks[0].size){
  47. chunks = [];
  48. return;
  49. }
  50. duration = (new Date().getTime() - startTime) / 1000;
  51. const newbolb = new Blob(chunks, { 'type': 'audio/mpeg' });
  52. const name = new Date().getDate() + '.mp3';
  53. const file = new File([newbolb], name)
  54. uni.uploadFile({
  55. url: UNI_APP.BASE_URL + '/file/upload',
  56. header: {
  57. accessToken: uni.getStorageSync("loginInfo").accessToken
  58. },
  59. file: file,
  60. name: 'file',
  61. success: (res) => {
  62. let r = JSON.parse(res.data);
  63. if (r.code != 200) {
  64. console.log(res)
  65. reject(r.message);
  66. } else {
  67. const data = {
  68. duration: parseInt(duration),
  69. url: r.data
  70. }
  71. resolve(data);
  72. }
  73. },
  74. fail: (e) => {
  75. reject(e);
  76. }
  77. })
  78. }
  79. })
  80. }
  81. export {
  82. checkIsEnable,
  83. start,
  84. close,
  85. upload
  86. }