play sound on click using jquery and mediaelement.js

匆匆过客 提交于 2019-12-11 01:57:26

问题


I have a design for a page that uses 3 types of audio and video:

  1. a few videos.
  2. a audio sound that triggers onclick.
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!