1.语音播报使用方式如下,由于安卓ios兼容性问题封装成不同组件
<common-audio ref="audioTip"></common-audio>
<wx-audio ref="audioWx"></wx-audio>
//红黄码播报语音
initAudio(){
let ran = navigator.userAgent
let isIOS = !!ran.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
// let isAndroid = ran.indexOf('Android') > -1 || ran.indexOf('Linux') > -1
let ua = window.navigator.userAgent.toLowerCase();
let isWX = ua.match(/MicroMessenger/i) == 'micromessenger'
if (isIOS && isWX) {
this.$refs.audioWx.start(this.flag)
}else {
this.$refs.audioTip.start(this.flag)
}
},
2.使用AudioContext进行语音播放 (安卓版微信和支付宝,ios支付宝有效 ),commonAudio.vue组件代码如下
<template>
<div></div>
</template>
<script>
export default {
name: "App",
data() {
return {
context:null,
source:null,
audioBuffer:null,
};
},
mounted() {
},
methods: {
start(flag){
window.AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.msAudioContext;
this.context = new window.AudioContext();
this.source = null;
this. audioBuffer = null;
if(flag==='R'){
this.loadAudioFile(require('../../../assets/mp3/red.mp3'))
}else if(flag==='Y'){
this.loadAudioFile(require('../../../assets/mp3/yellow.mp3'))
}
},
stopAudio() {
this.source.stop();
},
loadAudioFile(url) {
let _that = this
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function (e) {
_that.initSound(this.response);
};
xhr.send();
},
initSound(arrayBuffer) {
let _this = this
this.context.decodeAudioData(arrayBuffer, function (buffer) {
_this.audioBuffer = buffer;
_this.playSound();
}, function (e) {
console.log('Error decoding file', e);
});
},
playSound() {
this.source = this.context.createBufferSource();
this.source.buffer = this.audioBuffer;
this.source.loop = true;
this.source.connect(this.context.destination);
this.source.start();
},
},
};
</script>
3.使用audio 进行语音播放 (ios微信有效 ),wxiosAudio.vue组件代码如下
<template>
<audio :loop="true" id="mp3Btn" ref="audioTip" style="visibility: hidden">
<source :src="audio.src" />
</audio>
</template>
<script>
export default {
name: "App",
data() {
return {
audio: {
src: null
},
};
},
mounted() {
},
methods: {
start(flag) {
if(flag==='R'){
this.audio.src = require('../../../assets/mp3/red.mp3')
}else if(flag==='Y'){
this.audio.src = require('../../../assets/mp3/yellow.mp3')
}
if (typeof WeixinJSBridge === "undefined") {
document.addEventListener('WeixinJSBridgeReady',() => {
document.getElementById('mp3Btn').play();
}, false);
} else {
WeixinJSBridge.invoke("getNetworkType", {}, () => {
document.getElementById('mp3Btn').play();
});
}
},
},
};
</script>
|