微信游览器,解决安卓和ios自动播放音乐
弄巧成拙,解决了安卓和ios不可自动播放的问题,需要借助插件,这是目前找到的方法,如还能改进或有更好的方法还请分享。html代码,用于苹果的音乐播放<audio src="music.mp3"loop id="music"></audio>插件引用<script src="jquery-1.10.1.min.js"></script><scri
·
暂时解决了安卓和ios不可自动播放的问题。
html代码,用于苹果的音乐播放(苹果有一个开关调静音模式,使用html的audio播放,只要不把音量调到最低,还是可以出声) <audio id="audio" src="../music.mp3" loop autoplay></audio> <button id="start">start</button> <button id="stop">stop</button>
获取html的audio的dom let htmlAudio = document.querySelector('#audio')
// 这里是AudioContext给安卓用 window.AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.msAudioContext; var context = new window.AudioContext(); var source = null; var audioBuffer = null; function stopSound() { if (source) { source.stop(0); //立即停止 } } function playSound() { source = context.createBufferSource(); source.buffer = audioBuffer; source.loop = true; //循环播放 source.connect(context.destination); if (!(/iphone/.test(navigator.userAgent.toLowerCase()))) { source.start(0); //立即播放 } function initSound(arrayBuffer) { context.decodeAudioData(arrayBuffer, function(buffer) { //解码成功时的回调函数 audioBuffer = buffer; playSound(); }, function(e) { //解码出错时的回调函数 console.log('Error decoding file', e); }); } function loadAudioFile(url) { var xhr = new XMLHttpRequest(); //通过XHR下载音频文件 xhr.open('GET', url, true); xhr.responseType = 'arraybuffer'; xhr.onload = function(e) { //下载完成 initSound(this.response); }; xhr.send(); }
// 安卓,加载并播放 if (!(/iphone/.test(navigator.userAgent.toLowerCase()))) { loadAudioFile('../music.mp3'); }
// 这块是移动端ios自动播放 const invoke = () => { if (/iphone/.test(navigator.userAgent.toLowerCase())) { if (htmlAudio.paused) { htmlAudio.play() } } } if (typeof WeixinJSBridge === 'undefined') { document.addEventListener('WeixinJSBridgeReady', () => WeixinJSBridge.invoke('getNetworkType', {}, () => invoke()) ) } else { WeixinJSBridge.invoke('getNetworkType', {}, () => invoke()) }
// 按钮播放与暂停 $('#start').on('click', function() { if (/iphone/.test(navigator.userAgent.toLowerCase())) { htmlAudio.play() } else { playSound() } }) $('#stop').on('click', function() { if (/iphone/.test(navigator.userAgent.toLowerCase())) { htmlAudio.pause() } else { stopSound() } })
更多推荐
已为社区贡献1条内容
所有评论(0)