h5移动端audio消息声音提醒ios适配

实现效果:聊天中,有消息进入时声音提醒,主要运用audio标签。
注意:
①audio 标签src须静态值,若设置动态值,须audio对象 调用load()方法
②声音文件请用MP3格式,wav格式不兼容ios
③元素加载后,使用touchstart(h5)或 click(pc)事件初始化一次声音文件(play(), pause()), 初始化后,后续可主动触发声音播放
④初始化事件中,pause()后须设置currentTime为音频最大时间数(我这里是1s)
⑤每次触发播放前须设置currentTime为0(ios使用fastSeek()方法设置,设置后须load())
⑥播放完成后须设置currentTime为音频最大时间数(我这里是1s), 可通过监听audio对象的onended事件设置

以下具体代码:

PlayNotifyVoice播放声音组件

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
<template>
<audio controls id="audioPlay_z" src="/file/notification.mp3"></audio>
</template>

<script>
export default {
name: 'PlayNotifyVoice',
data () {
return {
audioFile: '/file/notification.mp3'
}
},
computed: {
isiOS () {
return !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) // ios
},
isSafari () {
const userAgent = navigator.userAgent
return userAgent.indexOf('Safari') > -1 && userAgent.indexOf('Chrome') === -1 && userAgent.indexOf('Edge') === -1 && userAgent.indexOf('OPR') === -1 // safari
}
},
beforeMount () {
if (this.isiOS) {
document.body.addEventListener('touchstart', this.init, false)
}
if (this.isSafari) {
document.body.addEventListener('click', this.init, false)
}
},
mounted () {
var audioEle = document.getElementById('audioPlay_z')
audioEle.addEventListener('ended', function (res) { // 暂停时会触发,当播放完一首歌曲时也会触发
if ('fastSeek' in audioEle) { // safari
audioEle.fastSeek(1) // 改变audio.currentTime的值
audioEle.load()
} else {
audioEle.currentTime = 1
}
})
},
methods: {
// 初始化
init () {
var audioEle = document.getElementById('audioPlay_z')
let playPromise = audioEle.play()
if (playPromise !== undefined) {
playPromise.then(() => {
audioEle.play()
audioEle.pause()
if ('fastSeek' in audioEle) { // safari
audioEle.fastSeek(1) // 改变audio.currentTime的值
} else {
audioEle.currentTime = 1
}
}).catch(() => {
console.log('play failed')
})
}
document.body.removeEventListener('touchstart', this.init, false)
document.body.removeEventListener('click', this.init, false)
},
// 播放消息提示音
playNotifyVoice () {
if (!!window.ActiveXObject || 'ActiveXObject' in window) { // IE内核浏览器
// eslint-disable-next-line
var OSPlayer = new ActiveXObject('WMPLayer.OCX')
OSPlayer.url = this.audioFile
OSPlayer.controls.play()
} else {
console.log('playNotifyVoice')
var audioEle = document.getElementById('audioPlay_z')
let playPromise = audioEle.play()
if (playPromise !== undefined) {
playPromise.then(() => {
if ('fastSeek' in audioEle) { // safari
audioEle.fastSeek(0) // 改变audio.currentTime的值
audioEle.load()
} else {
audioEle.currentTime = 0
}
audioEle.play()
}).catch(() => {
console.log('play failed')
})
}
}
}
}
}
</script>

<style lang="less" scoped>
#audioPlay_z {
display: none;
}
</style>
------ 本文结束------
坚持原创技术分享,您的支持将鼓励我继续创作!