使用jQuery单击另一个音频文件时停止/暂停音频

我创建了一个网站,其中包含我拍摄过的人的图像缩略图。 当访问者点击其中一个缩略图时,使用jQuery显示完整图像,并播放音频介绍。 我对每个缩略图/图像组合都有不同的音频介绍 – 目前有15个,每天添加更多。

我想确保如果访问者在上一个音频文件完成之前点击另一个缩略图,则停止/暂停前一个音频文件以允许播放新的音频文件 – 从而确保两个或多个轨道不同时播放。

我目前正在使用以下代码片段(包含在匿名函数中),在单击相应的缩略图时单独播放每个音频文件 – 因此每个音频文件都会复制此片段,但不知道如何确保它们不会互相玩耍。

$(".bridget-strevens").click(function(){ var audio = $('#bridget-strevens-intro')[0]; if (audio.paused){ audio.play(); } else { audio.pause(); } }); 

你能给我的任何帮助都会非常感激,因为我刚开始学习jQuery,并且没有足够的知识来提出可行的解决方案。

在此先感谢您的帮助!

为所有音频元素添加.audio类,并在单击音频时循环遍历所有音频元素。

 $(".bridget-strevens").click(function () { $('.audio').each(function (index, value) { if (!value.paused) { value.pause(); } }); var audio = $('#bridget-strevens-intro')[0]; if (audio.paused) { audio.play(); } else { audio.pause(); } }); 

如果这对你来说太沉重,那么只需在全局变量中添加音频元素,例如:

 var currentAudio; 

然后,当单击一个新音频时,只需暂停该音频,播放新音频并使用当前正在播放的新元素更新currentAudio变量。

 var currentAudio = null; $(".bridget-strevens").click(function () { if(currentAudio != null && !currentAudio.paused){ currentAudio.pause(); } var audio = $('#bridget-strevens-intro')[0]; if (audio.paused) { audio.play(); currentAudio = audio; } else { audio.pause(); } }); 

更新:

感谢您的快速回复! Grimbode,我已经尝试了你的建议,这似乎有效。 但是有能力停止和重置而不是暂停 – 所以如果他们在1完成之前点击1然后[2],然后再次点击1 ,那1将从头开始而不是暂停的点? 有没有办法检查状态’全局’,然后为每个单独的音频文件添加代码 – 只是为了保持代码量和重复下来? 再次感谢!! –

是。 播放音频并重新启动它 ,然后详细说明如何执行此操作。 最终结果如下所示:

 var currentAudio = null; $(".bridget-strevens").click(function () { if(currentAudio != null && !currentAudio.paused && currentAudio != this){ currentAudio.pause(); //Here we reset the audio and put it back to 0. currentAudio.currentTime = 0; } var audio = $('#bridget-strevens-intro')[0]; if (audio.paused) { audio.play(); currentAudio = audio; } else { audio.pause(); } }); 

您无法真正优化代码。 您将在每个音频元素上应用click事件。 您将不得不记住当前正在播放的音频元素,这样您就不必遍历所有音频文件。

如果你真的想要进一步发展,你可以创建一个库来处理一切。 这是一个例子:

 (function(){ var _ = function(o){ if(!(this instanceof _)){ return new _(o); } if(typeof o === 'undefined'){ o = {}; } //here you set attributes this.targets = o.targets || {}; this.current = o.current || null; }; //create fn shortcut _.fn = _.prototype = { init: function(){} } //Here you create your methods _.fn.load = function(){ //here you load all the files in your this.targets.. meaning you load the source //OR you add the click events on them. //returning this for chainability return this }; //exporting window._ = _; })(); //here is how you use it _({ targets: $('.audio') }).load();