问题
I have a design for a page that uses 3 types of audio and video:
- a few videos.
- a audio sound that triggers onclick.
- a audio loop that plays in the background, which the option to turn off.
MeidaElement.js looks just perfect for the videos, to get them all playing cross browser with the minimum of fuss.
It also seems to play audio well also. I'm just not sure if I can trigger a bit audio from a jQuery - i.e. just clicking on any old div. And if so, can I preload the audio so the sound happens immediately on click.
Thanks in advance for any pointers.
回答1:
This jQuery function seemed to work for me:
$('.button').click(function(){
$('audio')[0].player.play();
});
回答2:
You should be able to bind this to a div the same way you bind anything else to a div in jQuery. The samples at http://mediaelementjs.com/#installation will give you a good start for the method of creating your audio player. Specifically,
<script>
// JavaScript object for later use
var player = new MediaElementPlayer('#player',/* Options */);
// ... more code ...
player.pause();
player.setSrc('mynewfile.mp4');
// I'm removing the following play call so we can do it elsewhere
//player.play();
</script>
In the above, I removed the call to play() so I can bind it somewhere else. In jQuery, I think that should look like the following:
$('#divWhatever').on('click', function() { $('#player').play() } )
Please test this and report success or what failures you encounter. Regardless, the on function is what you are looking for in jQuery: http://api.jquery.com/on/
来源:https://stackoverflow.com/questions/11278890/play-sound-on-click-using-jquery-and-mediaelement-js