Javascript 如何停止 HTML5 的音频标签播放的音频

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3566967/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:13:55  来源:igfitidea点击:

How to stop audio played by audio tag of HTML5

javascriptaudiohtml

提问by Vijay Balkawade

I am new to HTML5 and I am exploring HTML5 features. There I came across audio tag.
I written code with it to play sound files.
I am having one problem with this tag. On button click, I want to change the sound file stopping the previous one.
I searched a lot but didn't find anything. Please help me to stop the sound played by audio tag.
Here is my code;

我是 HTML5 的新手,我正在探索 HTML5 功能。在那里我遇到了音频标签。
我用它编写了代码来播放声音文件。
这个标签有一个问题。单击按钮时,我想更改停止前一个的声音文件。
我搜索了很多,但没有找到任何东西。请帮我停止音频标签播放的声音。
这是我的代码;

  try
  {
       if(MyAudio != undefined)
       {
          MyAudio = null;
       }
       MyAudio = new Audio("filename");
       MyAudio.play();
  }
  catch(v)
  {
    //alert(v.message);
  }

采纳答案by Lekensteyn

Try this:

尝试这个:

  try
  {
       if(MyAudio != undefined)
       {
          MyAudio.pause();
       }
       MyAudio = new Audio("filename");
       MyAudio.play();
  }
  catch(v)
  {
    //alert(v.message);
  }

回答by Duefectu

As commented in this cuestión: HTML5 Audio stop function, a better solution could be:

正如此提示中所述:HTML5 音频停止功能,更好的解决方案可能是:

var sound = document.getElementById("audio");
sound.pause();
sound.currentTime = 0;