使用h5的audio,支持三种格式,我用的mp3格式,在vue页面中写的,并设置了播放时自动放大,变红动作
1、html <i>是图标,变色和放大用的,audio是隐藏的,loop是循环播放,controls是有播放暂停, muted为静音播放,此操作为解决谷歌禁用自动播放
<i class="el-icon-bell admin-header-setting" :style="{'color':alarmColor,'transform':alarmScale}"></i>告警
<audio :src="alarmAudioDefault" ref="myaudio" controls="controls" loop="true" muted="true" v-show="false"></audio>
2、变量
data() {
return {
alarmAudioDefault: "/audio/6.mp3",
alarmColor: "",
alarmScale: "scale(1)",
ws: null
}
}
3、我是用的WebSocket触发的
mounted() {
// 此操作是为了任意点击解锁静音,实现谷歌自动播放
document.body.addEventListener(
"mousedown",
() => {
this.$refs.myaudio.muted = false
document.body.removeEventListener("mousedown", () => {})
},
false
)
// 接收消息来触发
this.initWS()
},
methods: {
autoPlay() {
var myAuto = this.$refs.myaudio
this.alarmColor = "#ff0000"
this.alarmScale = "scale(1.3)"
myAuto.play()
setTimeout(() => {
this.closePlay()
}, 7000) // 七秒后自动停止播放
},
closePlay() {
var myAuto = this.$refs.myaudio
myAuto.pause()
myAuto.load()
this.alarmColor = "#ffffff"
this.alarmScale = "scale(1)"
},
initWS() {
if ("WebSocket" in window) {
try {
this.ws = new WebSocket(
"ws://" + window.location.host + "/ws/alarms"
)
this.ws.onopen = () => {
if (this.alarmAudio) {
this.alarmAudioDefault = this.alarmAudio
}
this.ws.send("FirstConnection")
}
this.ws.onmessage = (evt) => {
if (evt.data !== "FirstConnection") {
this.autoPlay()
}
}
this.ws.onclose = () => {}
this.ws.onerror = () => {
this.notifyInfo("webSocket 连接失败!")
}
} catch (error) {
this.notifyInfo("webSocket 连接失败!")
}
}
},
notifyInfo(message) {
this.$notify({
title: "提醒",
message: message,
offset: 200
})
}
},
destroyed() {
document.body.removeEventListener("mousedown", () => {})
}