main.vue 2.5 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. <el-icon>
  15. <Icon v-if="playing !== true" icon="ep:video-play" />
  16. <Icon v-else icon="ep:video-pause" />
  17. <span class="amr-duration" v-if="duration">{{ duration }} 秒</span>
  18. </el-icon>
  19. <div v-if="content">
  20. <el-tag type="success" size="mini">语音识别</el-tag>
  21. {{ content }}
  22. </div>
  23. </div>
  24. </template>
  25. <script setup lang="ts" name="WxVoicePlayer">
  26. // 因为微信语音是 amr 格式,所以需要用到 amr 解码器:https://www.npmjs.com/package/benz-amr-recorder
  27. import BenzAMRRecorder from 'benz-amr-recorder'
  28. const props = defineProps({
  29. url: {
  30. type: String, // 语音地址,例如说:https://www.iocoder.cn/xxx.amr
  31. required: true
  32. },
  33. content: {
  34. type: String, // 语音文本
  35. required: false
  36. }
  37. })
  38. const amr = ref()
  39. const playing = ref(false)
  40. const duration = ref()
  41. /** 处理点击,播放或暂停 */
  42. const playVoice = () => {
  43. // 情况一:未初始化,则创建 BenzAMRRecorder
  44. if (amr.value === undefined) {
  45. amrInit()
  46. return
  47. }
  48. // 情况二:已经初始化,则根据情况播放或暂时
  49. if (amr.value.isPlaying()) {
  50. amrStop()
  51. } else {
  52. amrPlay()
  53. }
  54. }
  55. /** 音频初始化 */
  56. const amrInit = () => {
  57. amr.value = new BenzAMRRecorder()
  58. // 设置播放
  59. amr.value.initWithUrl(props.url).then(function () {
  60. amrPlay()
  61. duration.value = amr.value.getDuration()
  62. })
  63. // 监听暂停
  64. amr.value.onEnded(function () {
  65. playing.value = false
  66. })
  67. }
  68. /** 音频播放 */
  69. const amrPlay = () => {
  70. playing.value = true
  71. amr.value.play()
  72. }
  73. /** 音频暂停 */
  74. const amrStop = () => {
  75. playing.value = false
  76. amr.value.stop()
  77. }
  78. // TODO 芋艿:下面样式有点问题
  79. </script>
  80. <style lang="scss" scoped>
  81. .wx-voice-div {
  82. padding: 5px;
  83. background-color: #eaeaea;
  84. border-radius: 10px;
  85. }
  86. .amr-duration {
  87. font-size: 11px;
  88. margin-left: 5px;
  89. }
  90. </style>