RecorderManager.js 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. // #ifdef H5
  2. import Recorder from 'recorder-core';
  3. import 'recorder-core/src/engine/mp3';
  4. import 'recorder-core/src/engine/mp3-engine';
  5. // #endif
  6. export default class RecorderManager {
  7. recorder = null;
  8. //录音开始时间
  9. uniStartTime = null;
  10. //语音录音中
  11. recording = false;
  12. onRecordingComplete = null;
  13. constructor() {
  14. // #ifdef H5
  15. this.recorder = Recorder({
  16. type : 'mp3',
  17. sampleRate:16000,//录音的采样率,越大细节越丰富越细腻
  18. bitRate:16,//录音的比特率,越大音质越好
  19. onProcess : function () {}
  20. });
  21. // #endif
  22. // #ifndef H5
  23. this.recorder = uni.getRecorderManager();
  24. // #endif
  25. }
  26. onRecordComplete(callBack) {
  27. this.onRecordingComplete = callBack;
  28. // #ifndef H5
  29. this.initUniRecorder();
  30. // #endif
  31. }
  32. initUniRecorder() {
  33. //录音结束后,发送
  34. this.recorder.onStop((res) => {
  35. const duration = Date.now() - this.uniStartTime;
  36. res.duration = duration;
  37. this.onRecordingComplete(res, duration);
  38. });
  39. // 监听录音报错
  40. this.recorder.onError((e) => {
  41. this.recording = false;
  42. this.recorder.stop();
  43. console.log('录音失败:', e);
  44. })
  45. }
  46. authorize() {
  47. return new Promise((resolve,reject) => {
  48. // #ifdef H5
  49. this.recorder.open(() => {
  50. resolve();
  51. }, (e) => {
  52. this.recorder.close();
  53. reject(e);
  54. });
  55. // #endif
  56. // #ifndef H5
  57. if (uni.authorize) {
  58. uni.authorize({
  59. scope: 'scope.record',
  60. success() {
  61. resolve()
  62. },
  63. fail: (e) => {
  64. reject(e)
  65. }
  66. });
  67. }
  68. // #endif
  69. });
  70. }
  71. start() {
  72. this.recording = true;
  73. // #ifdef H5
  74. this.recorder.start();
  75. // #endif
  76. // #ifndef H5
  77. try {
  78. // 更多配置参考uniapp:https://uniapp.dcloud.net.cn/api/media/record-manager.html#getrecordermanager
  79. this.recorder.start({
  80. duration: 600000 // 指定录音的时长,单位 ms
  81. });
  82. this.uniStartTime = Date.now();
  83. } catch (e) {
  84. console.log(e);
  85. }
  86. // #endif
  87. }
  88. stop() {
  89. this.recording = false;
  90. // #ifdef H5
  91. this.recorder.stop((blob, duration) => {
  92. const file = new File([blob], 'audio.mp3', {type: blob.type});
  93. file.tempFilePath = URL.createObjectURL(blob);
  94. file.duration = duration;
  95. this.onRecordingComplete(file, duration);
  96. }, (msg) => {
  97. console.log('录音失败:',msg)
  98. })
  99. // #endif
  100. // #ifndef H5
  101. try {
  102. this.recorder.stop();
  103. } catch (e) {
  104. console.log(e);
  105. }
  106. // #endif
  107. }
  108. }