若是咱們想要在一個頁面自動播放背景音樂或是其餘音頻,好比ios是沒辦法調用audio.play()事件直接調用,非得添加手動點擊事件才能夠。接下來就說說我在項目裏遇到的困難和解決辦法.
狀況一、咱們知道安卓是能夠直接調用音頻的play事件的,ios不行。如是在單獨的h5頁面,無路由,這種狀況就必須加個引導按鈕點擊它,或是在頁面全局設置一個點擊事件one,當用戶第一次且僅第一次碰到頁面就播放。這裏用vue距舉例:vue
<template> <view v-on:touchstart.once="playBgMusic()"></view> </template> methods: { playBgMusic () { let isiOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); if (isiOS) this.bgMusic.play(); } } mounted(){ this.bgMusic = new Audio(); this.bgMusic.loop = true; this.bgMusic.src = require('xxx.mp3'); this.bgMusic.load(); this.bgMusic.play(); }
狀況二、若是是當用戶使用hash或者有路由跳轉的狀況,能夠使用在跳轉頁添加全局audio對象的方式來控制。這裏使用vue舉例:首先可在router/index.js裏設置window.audio=null,在跳轉前的頁面new一個video 並將此對象賦予window.audio,而後便可在下一個頁面使用audio對象。代碼:ios
/*router/index.js*/ window.bgMusic=null; /*跳轉頁面 router/beforeGo.js 跳轉事件*/ <view @click="goTo()">跳轉到自動播放音樂的頁面</view> methods: { goTo () { const audio = new Audio(); audio.addEventListener('canplay', () => {audio.play()}); audio.loop = true; audio.src = mathBgVoice; audio.load(); bgMusic = audio; this.$router.replace('自動播放音樂的頁面路由') } }
狀況3:若是你的業務主要是在微信上,那麼能夠使用如下代碼,可實如今微信瀏覽器中iOS和安卓設備中自動播放音頻的效果:瀏覽器
var play = function() { document.removeEventListener("WeixinJSBridgeReady", play); document.removeEventListener("YixinJSBridgeReady", play); audioCtx.play(); }; document.addEventListener("WeixinJSBridgeReady",play, false); document.addEventListener('YixinJSBridgeReady', play, false);
這樣處理之後,在跳轉頁面先尋找播放時機,等跳轉到播放音樂的頁面便可實現‘自動播放背景音樂’的功能。微信