简体   繁体   中英

Playing HTML5 audio from mobile devices from callback

I want to be able to play an audio file from a callback function using javascript and HTML5 elements. From what I've read, the only way that most mobile devices play HTML5 audio is via user interaction (ie button click etc).

My scenario is slightly different. The button click event makes an ajax call with a callback function, and based on the results returned, a different sound is supposed to be played. This works fine on desktop browsers, however both android and the iPad do not seem to support this.

Does anyone know of any workarounds?

Sample code showing how audio objects are initialised etc:

    var sound = new Audio('Sample.wav');
    var sound2 = new Audio('Sample2.wav');

/// Button events etc here, stock standard stuff

    function MyCallBack(e)
    {
      if(e.someValue)
       sound.play();
      else
       sound2.play();
    }

EDIT: I've solved this problem using a similar solution as outlined below. On the user event I played then immediately paused the sounds. Once the callback returned, I resumed playing the appropriate sound

 hit.play(); hit.pause(); fail.play(); fail.pause();

You might try placing both sounds into a single audio file, and then using the callback to queue up and play at the correct location.

Going this route, you can start playing the sound on the initial user click (with empty space at the beginning) and then immediately pause it (from the play event to ensure it began playing). Once the callback comes in, set the currentTime to the place on the audio track you want to play and begin playing. Playing this way should work, because the initial play call occurred on a user action.

To extend on Derek's answer, here's the jQuery code to make this happen for a given audio element:

<audio preload="auto" id="yourHTMLaudio">
    <source src="/sounds/youraudio.ogg" type="audio/ogg">
    <source src="/sounds/youraudio.mp3" type="audio/mpeg">
    <source src="/sounds/youraudio.wav" type="audio/wav">
</audio>

On the button's click event, call the following:

$("#yourbutton").on("click", function() {
    ...
    $("#yourHTMLaudio").trigger('play').trigger('pause').prop("currentTime", 0);
    ...

Then in your Ajax done() function you can just play it like you normally would:

    ...
    $.ajax({
        ...
    }).done(function(msg) {
        ...
        $("#yourHTMLaudio").trigger('play');
        ...
    });
    ...
});

HTML5 audio tag is supported in almost all of the smart phone browsers these days

Try

    <audio autoplay="autoplay" controls="controls">  
       <source src="music.ogg" />  
       <source src="music.mp3" />  
    </audio> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM