record.vue 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <template>
  2. <div :style="`color:${show ? '#00CED1':'rgba(0, 0, 0, 0.3)'}`">&#xe6c1;</div>
  3. </template>
  4. <script>
  5. export default {
  6. props: ["audioState"],
  7. data() {
  8. return {
  9. chunks: [],
  10. mediaRecorder: null,
  11. show: false, // true 开启,false 停止
  12. };
  13. },
  14. methods: {
  15. // 初始化音频
  16. async initRecorder() {
  17. try {
  18. const stream = await navigator.mediaDevices.getUserMedia({
  19. audio: true,
  20. });
  21. this.mediaRecorder = new MediaRecorder(stream);
  22. // 事件监听
  23. this.mediaRecorder.ondataavailable = (e) => {
  24. this.chunks.push(e.data);
  25. };
  26. this.mediaRecorder.onstart = () => {
  27. this.chunks = [];
  28. };
  29. this.mediaRecorder.onstop = () => {
  30. const blob = new Blob(this.chunks, {
  31. type: "audio/webm;codecs=opus",
  32. });
  33. this.$emit("callBack", blob);
  34. };
  35. } catch (error) {
  36. this.show = false;
  37. this.mediaRecorder = null;
  38. let txt = "不支持的音频";
  39. if (error.toString().includes("getUserMedia")) {
  40. txt = "不支持webrtc音频";
  41. } else {
  42. txt = "未获取到音频设备";
  43. }
  44. alert(txt)
  45. }
  46. },
  47. // blob2AudioBuffer
  48. blob2audioBuffer(blob) {
  49. const reader = new FileReader();
  50. reader.onload = function () {
  51. console.log(123, this.result);
  52. const audioCtx = new AudioContext();
  53. audioCtx.decodeAudioData(this.result, function (audioBuffer) {
  54. // AudioBuffer
  55. console.log(audioBuffer);
  56. });
  57. };
  58. reader.readAsArrayBuffer(blob);
  59. },
  60. },
  61. watch: {
  62. audioState(v) {
  63. if (!this.mediaRecorder) return;
  64. if (v) {
  65. this.mediaRecorder.start();
  66. } else {
  67. this.mediaRecorder.stop();
  68. }
  69. this.show = v;
  70. },
  71. },
  72. mounted() {
  73. this.initRecorder();
  74. },
  75. };
  76. </script>