javascript - 单击链接时重置音频

标签 javascript html audio

当我播放音频时,暂停音频,单击外部链接,然后返回到音频所在的页面,我希望音频重置而不是离开我上次停下的地方,但它离开了我的位置离开了。

在我的 HTML5 页面中,我在结束正文标记之前添加了此链接: src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">

HTML5:

<table id="multiplemp3">
    <tr>
       <th>
        <audio controls>
            <source src="http://geo-samples.beatport.com/lofi/5005876.LOFI.mp3" type="audio/mpeg">
Your browser does not support the audio element.
            </audio>
    </th>
</tr>
<tr>
    <th>
        <audio controls>
            <source src="http://geo-samples.beatport.com/lofi/5005933.LOFI.mp3" type="audio/mpeg">
Your browser does not support the audio element.
        </audio>
    </th>
</tr>
<tr>
</tr>
</table>
<br>


<p><a href="https://en.wikipedia.org/wiki/Main_Page">More . . .</a></p>
<p><a href="https://en.wikipedia.org/wiki/Main_Page">Return to Home Page</a></p>

JS:

/* allows user to play one mp3 at a time */

/* declare variables: get tag from html */
var audios = document.getElementsByTagName("audio");

var links = document.getElementsByTagName("a");

/* bind() is used for binding audio attribute and parameters of a function call, audio is the current audio element played( comes from the binding above), we compare each element in audios with this, and pause all those which are not matching. */

for (var i=0; i<audios.length;i++)  {
  audios[i].onplay = pauseAllAudios.bind(null, audios[i]); 
}

function pauseAllAudios(audio) {
    for(var i=0; i<audios.length;i++)
       if(audios[i]!=audio)  {
         audios[i].pause();    
       } else if (links.click() ) {
            audios[i].stop();    
      }
};

http://jsfiddle.net/0eun4kcy/1/

最佳答案

您可以在暂停按钮上设置一个事件监听器,然后自动将音频的 currentTime 设置为零。例如,如果您有一个音频元素,您可以:

var audio = document.getElementsByTagName("audio");

audio.onpause = function() {
     audio.currentTime = 0;
};

这将重置音频文件。下次用户单击暂停按钮时,将从头开始播放。

关于javascript - 单击链接时重置音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31908462/

相关文章:

javascript - 添加动态数据后如何获取对 HTML 下拉菜单的引用

javascript - 为什么局部作用域不引用全局变量?

javascript - 如何裁剪 IFrame 的内容(从 IFrame 容器,不使用滚动)

javascript - 如何解码二进制音频数据?

audio - 实现小组,低延迟,一对多音频广播的最简单方法是什么

javascript - 我如何检查一个窗口是否已在 JavaScript 中关闭?

javascript - 在窗口调整大小时引导更改按钮文本大小

javascript - 如何使用 jquery 启用/禁用 div 层

c# - 带有 Html.EditorFor 的表格

javascript - html5 显示音频当前时间