ios版微信
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") { //未执行WeixinJSBridge 开始监听 WeixinJSBridge document.addEventListener('WeixinJSBridgeReady',() => { document.getElementById('mp3Btn').play(); }, false); } else { //已经执行 使用 getNetworkType 调用获取网络类型后执行 WeixinJSBridge.invoke("getNetworkType", {}, () => { document.getElementById('mp3Btn').play(); }); } },
安卓版微信、安卓、ios版支付宝
<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下载音频文件 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>