sound-element.vue
2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<template>
<message-bubble :isMine=isMine :message=message>
<div class="sound-element-wrapper" title="单击播放" @click="play">
<i class="iconfont icon-voice"></i>
{{ second + '"' }}
</div>
</message-bubble>
</template>
<script>
import MessageBubble from '../message-bubble'
export default {
name: 'SoundElement',
props: {
payload: {
type: Object,
required: true
},
message: {
type: Object,
required: true
},
isMine: {
type: Boolean
}
},
components: {
MessageBubble
},
data() {
return {
amr: null
}
},
computed: {
url() {
return this.payload.url
},
size() {
return this.payload.size
},
second() {
return this.payload.second
}
},
methods: {
play() {
// 目前移动端的语音消息采用 aac 格式,以前用 amr 格式。默认先用 audio 标签播放,若无法播放则尝试 amr 格式播放。
const audio = document.createElement('audio')
audio.addEventListener('error', this.tryPlayAMR) // 播放出错,则尝试使用 AMR 播放
audio.src = this.url
const promise = audio.play()
if (promise) {
promise.catch(() => {})
}
},
tryPlayAMR() {
try {
const isIE = /MSIE|Trident|Edge/.test(window.navigator.userAgent)
// amr 播放组件库在 IE 不支持
if (isIE) {
this.$store.commit('showMessage', {
message: '您的浏览器不支持该格式的语音消息播放,请尝试更换浏览器,建议使用:谷歌浏览器',
type: 'warning'
})
return
}
// 动态插入 amr 播放组件库
if (!window.BenzAMRRecorder) {
const script = document.createElement('script')
script.addEventListener('load', this.playAMR)
script.src = './BenzAMRRecorder.js'
const firstScript = document.getElementsByTagName('script')[0]
firstScript.parentNode.insertBefore(script, firstScript)
return
}
this.playAMR()
} catch (error) {
this.$store.commit('showMessage', {
message: '您的浏览器不支持该格式的语音消息播放,请尝试更换浏览器,建议使用:谷歌浏览器',
type: 'warning'
})
}
},
playAMR() {
if (!this.amr && window.BenzAMRRecorder) {
this.amr = new window.BenzAMRRecorder()
}
if (this.amr.isInit()) {
this.amr.play()
return
}
this.amr.initWithUrl(this.url).then(() => {
this.amr.play()
})
}
}
}
</script>
<style lang="stylus" scoped>
.sound-element-wrapper {
padding: 0px 10px;
cursor: pointer;
}
</style>