Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
381 views
in Technique[技术] by (71.8m points)

html - Playing audio on iPad

I'm working on a website that has a chat for a client, however, we're experiencing problems with audio in iPad (iOS 5).

The target is in fact the iPad with support for IE7 is preferred.

I've tried these approaches:

HTML5

<audio id="notification" preload="auto">
    <source src="audio/notification.ogg" type="audio/ogg" />
    <source src="audio/notification.mp3" type="audio/mpeg" />
</audio>

With some javascript

var el = document.getElementById('notification');
el.play();

Some javascript function I stole somewhere which in fact are two different methods in one function. Please note the script is in a subdir, so the path is correct.

function notify() {
    var url = '../audio/notification.mp3';
    var a = document.createElement('audio');

    if(!!(a.canPlayType && a.canPlayType('audio/mpeg').replace(/no/, ''))) {
        var sound = new Audio(url);
        sound.load();
        sound.play();
    } else {
        $('#notification').remove();
        var sound = $('<embed id="notification" type="audio/mpeg" src="'+url+'" loop="false" hidden="true" autostart="true" />');
        $(body).append(sound);
    }
}

Both methods doesn't seem to work. Am I doing something wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well, the answer was somewhat obvious.

After a lot of time spending doing research etc, I've found an article in the official documentation of Safari saying:

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.

So, basically, you can't launch a sound without the user triggering it at first. As solution I created a mute button that is off on default, so you have to click it which plays the notification sound. Afterwards I can use Javascript to play the sound without user interaction.

Thank you Safari for this great future. Thanks a lot.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...