recorder-h5.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. console.log("start record")
  28. startTime = new Date().getTime();
  29. chunks = [];
  30. stream = audioStream;
  31. rc = new MediaRecorder(stream)
  32. rc.start()
  33. })
  34. }
  35. let close = () => {
  36. console.log("stream:", stream)
  37. stream.getTracks().forEach((track) => {
  38. track.stop()
  39. })
  40. rc.stop()
  41. }
  42. let upload = () => {
  43. return new Promise((resolve, reject) => {
  44. rc.ondataavailable = (e) => {
  45. console.log("ondataavailable:",e.data)
  46. console.log("size:",e.data.size)
  47. console.log("type:",e.data.type)
  48. chunks.push(e.data)
  49. }
  50. rc.onstop = () => {
  51. if(!chunks[0].size){
  52. chunks = [];
  53. return;
  54. }
  55. duration = (new Date().getTime() - startTime) / 1000;
  56. console.log("时长:", duration)
  57. console.log("上传,chunks:", chunks.length)
  58. const newbolb = new Blob(chunks, { 'type': 'audio/mpeg' });
  59. const name = new Date().getDate() + '.mp3';
  60. const file = new File([newbolb], name)
  61. uni.uploadFile({
  62. url: UNI_APP.BASE_URL + '/file/upload',
  63. header: {
  64. accessToken: uni.getStorageSync("loginInfo").accessToken
  65. },
  66. file: file,
  67. name: 'file',
  68. success: (res) => {
  69. let r = JSON.parse(res.data);
  70. if (r.code != 200) {
  71. console.log(res)
  72. reject(r.message);
  73. } else {
  74. const data = {
  75. duration: parseInt(duration),
  76. url: r.data
  77. }
  78. resolve(data);
  79. }
  80. },
  81. fail: (e) => {
  82. reject(e);
  83. }
  84. })
  85. }
  86. })
  87. }
  88. export {
  89. checkIsEnable,
  90. start,
  91. close,
  92. upload
  93. }