【问题标题】:Reset Audio when I click on a link单击链接时重置音频
【发布时间】:2015-11-01 17:06:04
【问题描述】:

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

在我的 HTML5 页面中,我在结束 body 标记之前包含了这个链接: 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/

【问题讨论】:

  • 我试过在 Microsoft Edge 和 Firefox 上打开小提琴,当你返回时,音频都停止并设置为 0s。
  • 当我在本地服务器上测试它时它不起作用。但由于我使用的是这个库:“ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js”也许我必须在服务器上测试它。谢谢你告诉我。

标签: javascript html audio


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-31
    • 2013-05-13
    • 1970-01-01
    • 2019-02-07
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多