main.vue 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <!--
  2. - Copyright (C) 2018-2019
  3. - All rights reserved, Designed By www.joolun.com
  4. 【微信消息 - 语音】
  5. 芋道源码:
  6. ① bug 修复:
  7. 1)joolun 的做法:使用 mediaId 从微信公众号,下载对应的 mp4 素材,从而播放内容;
  8. 存在的问题:mediaId 有效期是 3 天,超过时间后无法播放
  9. 2)重构后的做法:后端接收到微信公众号的视频消息后,将视频消息的 media_id 的文件内容保存到文件服务器中,这样前端可以直接使用 URL 播放。
  10. ② 代码优化:将 props 中的 objData 调成为 data 中对应的属性,并补充相关注释
  11. -->
  12. <template>
  13. <div class="wx-voice-div" @click="playVoice">
  14. <i :class="playing !== true ? 'el-icon-video-play': 'el-icon-video-pause'">
  15. <span class="amr-duration" v-if="duration">{{ duration }}</span>
  16. </i>
  17. <div v-if="content">
  18. <el-tag type="success" size="mini">语音识别</el-tag>
  19. {{ content }}
  20. </div>
  21. </div>
  22. </template>
  23. <script>
  24. // 因为微信语音是 amr 格式,所以需要用到 amr 解码器:https://www.npmjs.com/package/benz-amr-recorder
  25. const BenzAMRRecorder = require('benz-amr-recorder')
  26. export default {
  27. name: "wxVoicePlayer",
  28. props: {
  29. url: { // 语音地址,例如说:https://www.iocoder.cn/xxx.amr
  30. type: String,
  31. required: true
  32. },
  33. content: { // 语音文本
  34. type: String,
  35. required: false
  36. }
  37. },
  38. data() {
  39. return {
  40. amr: undefined, // BenzAMRRecorder 对象
  41. playing: false, // 是否在播放中
  42. duration: undefined, // 播放时长
  43. }
  44. },
  45. methods:{
  46. playVoice() {
  47. debugger
  48. // 情况一:未初始化,则创建 BenzAMRRecorder
  49. if (this.amr === undefined){
  50. this.amrInit();
  51. return;
  52. }
  53. if (this.amr.isPlaying()) {
  54. this.amrStop();
  55. } else {
  56. this.amrPlay();
  57. }
  58. },
  59. amrInit() {
  60. const amr = new BenzAMRRecorder();
  61. this.amr = amr;
  62. // 设置播放
  63. const that = this
  64. amr.initWithUrl(this.url).then(function() {
  65. that.amrPlay()
  66. that.duration = amr.getDuration();
  67. })
  68. // 监听暂停
  69. amr.onEnded(function() {
  70. that.playing = false;
  71. })
  72. },
  73. amrPlay() {
  74. this.playing = true;
  75. this.amr.play()
  76. },
  77. amrStop() {
  78. this.playing = false;
  79. this.amr.stop()
  80. },
  81. }
  82. };
  83. </script>
  84. <style lang="scss" scoped>
  85. .wx-voice-div {
  86. padding: 5px;
  87. background-color: #eaeaea;
  88. border-radius: 10px;
  89. }
  90. .amr-duration {
  91. font-size: 11px;
  92. margin-left: 5px;
  93. }
  94. </style>