前幾天作了一個H5活動頁面,產品要求初始化播放音樂,因曉得H5 Audio標籤支持Autoplay就沒在乎。 完了在手機上測試,發現手機上打開頁面死活就是不會自動播放,點擊播放按鈕才能夠播放,非常糾結。 而後網上查了下發現iOS上禁止了Audio的Autoplay屬性,緣由以下:html
User Control of Downloads Over Cellular Networks
In Safari on iOS (for all devices, including iPad), where the user may be on a cellular network and be charged per data unit, preload and autoplay are disabled. No data is loaded until the user initiates it. This means the JavaScript play() and load() methods are also inactive until the user initiates playback, unless the play() or load() method is triggered by user action. In other words, a user-initiated Play button works, but an onLoad="play()" event does not.html5
This plays the movie: <input type="button" value="Play" onclick="document.myMovie.play()"> This does nothing on iOS: <body onload="document.myMovie.play()">
詳細查看Safari HTML5 Audio and Video Guideios
藉助Google翻譯瞭解到:蘋果爲了用戶着想,禁止了Autoplay和JS "onload" 加載播放。ajax
官方禁用,和產品溝通了下,產品發了"友站"網頁給我說是可讓我參考下,確實能夠,但代碼太多,棄之。微信
仍是去http://search.yahoo.com找答案了,在IBM開發者找到了答案:app
// run on page load var audio = document.getElementById('audio'); jQuery.ajax({ url: 'ajax.js', async: false, success: function() { audio.play(); // audio will play in iOS before 4.2.1 } });
詳細查看IBM開發者less
但iOS4.2.1之後就失效了,如今都iOS8了,真是無語了,但也沒找到其它方法,就死馬當活馬醫試一下,結果,神奇的一幕出現了,打開居然自動播放音樂了,哈哈哈...async
不是說失效了麼,這是爲什麼呢?哦,剛纔只是在微信裏打開的,我再用Safari打開就不會自動播放音樂了,還好,咱們H5活動僅限微信裏面打開。ide
好了,不過Bug立刻又來了,測試發現一臺安卓機在微信裏打開也不能自動播放,我拿來試了下,確實如此,而後打開"友站"的發現也是不能自動播放,產品確認了下,讓參考"友站"的優化一下,就是觸摸一下就會自動播放。測試
document.addEventListener('touchstart', function(){ audio.play(); }, false);
此次是真的好了,除了那臺Android5.x系統的手機,其它在微信打開均可以自動播放了。
總結一下吧:
國內流量很貴的,哎喲個人錢啊。 咱們經過"投機"繞過系統限制而達到了目的,這樣真的好嗎?
這樣對用戶的體驗真的好嗎?
咱們真的值得這樣作麼?