使用 JavaScript 动态控制 HTML5 音频
我有一个类似的画廊,其中有 10 个左右的缩略图,每个缩略图代表一首歌曲。为了控制每个播放,我设置了一个播放按钮以通过 jQuery 淡入。在对 Apple 开发中心进行一番挖掘后,我发现了一些用于控制音频的原生 JavaScript。它工作得很好,但是是为一次控制一个对象而编写的。我想做的是将其重写为一个函数,可以动态控制您所选择的缩略图的播放/暂停。
下面是我发现的代码.. 有效,但是编写 10 次会产生很多不必要的代码。
感谢您的帮助和建议,永远!
HTML:
<div class="thumbnail" id="paparazzixxx">
<a href="javascript:playPause();">
<img id="play" src="../images/icons/35.png" />
</a>
<audio id="paparazzi">
<source src="../audio/fernando_garibay_paparazzisnlmix.ogg" type="audio/ogg" />
<source src="../audio/fernando_garibay_paparazzisnlmix.mp3" type="audio/mpeg" />
Your browser does not support HTML5 audio.
</audio>
</div>
JavaScript:
<script type="text/javascript">
function playPause() {
var song = document.getElementsByTagName('audio')[0];
if (song.paused)
song.play();
else
song.pause();
}
</script>
I've got a gallery of sorts with 10 or so thumbnails that each represent one song. To control the playback of each, I've set a play button to fades in via jQuery. After some digging around Apple's Dev Center I found some native JavaScript to control audio. It works beautifully, but is written for control of one object at a time. What I'd like to do is rewrite it as one function that dynamically controls the playback/pause of the thumbnail you're selecting.
Below is the code that I found.. works, but it'd be a lot of unnecessary code to write it 10 times.
Thanks for your help and advice, always!
HTML:
<div class="thumbnail" id="paparazzixxx">
<a href="javascript:playPause();">
<img id="play" src="../images/icons/35.png" />
</a>
<audio id="paparazzi">
<source src="../audio/fernando_garibay_paparazzisnlmix.ogg" type="audio/ogg" />
<source src="../audio/fernando_garibay_paparazzisnlmix.mp3" type="audio/mpeg" />
Your browser does not support HTML5 audio.
</audio>
</div>
JavaScript:
<script type="text/javascript">
function playPause() {
var song = document.getElementsByTagName('audio')[0];
if (song.paused)
song.play();
else
song.pause();
}
</script>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
jQuery 对于这类事情来说非常棒。它使您能够根据元素与 DOM 树中其他元素的关系轻松地操作元素。在您的示例中,您希望能够使
元素在单击时仅影响其旁边的
元素。
当前 Javascript 代码的问题在于,它实际上只是抓取整个页面上的第一个音频元素。
以下是如何更改代码以支持无限数量的
。 & <音频>
对。标记(在我的示例中为“playback”)
HTML
Javascript
jQuery is awesome for this sort of thing. It gives you the ability to easily manipulate elements based on their relationship to other elements in the DOM tree. In your example you want to be able to make the
<a>
elements only affect the<audio>
elements that are right next to them when clicked.The problem with your current Javascript code is that it is actually just grabbing only the first audio element on the entire page.
Here's how you can change your code to support an unlimited number of
<a> & <audio>
pairs.<a>
tag ('playback' in my example)HTML
Javascript