简体   繁体   English

如何通过单击按钮切换音频play()pause()?

[英]How to toggle audio play() pause() with a button click?

I have added an audio to my website, which is playing when site is opened. 我已将音频添加到我的网站,该音频在打开网站时正在播放。 Now I want add play/pause button to toggle the audio. 现在,我想添加播放/暂停按钮来切换音频。

This is how I tried it: 这是我尝试的方法:

<audio id="myAudio" autoplay >
 <source src="mp3/background-music.mp4" type='audio/mp4'>
 Your user agent does not support the HTML5 Audio element.
</audio>

<a type="button" class="play-pause" title="play/pause"><i class="fa fa-pause"></i></a>


<script type="text/javascript">
  $(document).ready(function() {
    var playing = false;

    $('a.audio-btn').click(function() {
        if (playing == false) {
            document.getElementById('myAudio').play();
            playing = true;
            $(this).text("stop sound");

        } else {
            document.getElementById('myAudio').pause();
            playing = false;
            $(this).text("restart sound");
        }
    });
  });
</script>  

But its not working for me. 但是它对我不起作用。 Can anybody tell me where I have gone wrong? 谁能告诉我我哪里出问题了?

将您的$('a.audio-btn')更改为$('a.play-pause')

For demo purpose, i add video tag, to work with audio you can replace video to audio tag and Use 出于演示目的,我添加了video标签,要使用音频,您可以将video替换为audio标签并使用

$('.play-pause')

Instead of 代替

$('a.audio-btn')

For audio use this at the place of video tag : 对于音频,请在video标签的位置使用:

<audio id="myAudio" autoplay>
 <source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" type='audio/mp4'>
   Your user agent does not support the HTML5 Audio element.
</audio>

 $(document).ready(function () { var playing = true; $('.play-pause').click(function () { if (playing == false) { document.getElementById('myAudio').play(); playing = true; $(this).text("Sop Sound"); } else { document.getElementById('myAudio').pause(); playing = false; $(this).text("Restart Sound"); } }); }); 
 a { background: #000; color: #fff; cursor: pointer; padding: 10px; } video { width: 200px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <video id="myAudio" autoplay> <source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" type='video/mp4'> Your user agent does not support the HTML5 Audio element. </video> <a type="button" class="play-pause" title="play/pause">Play / Pause</a> 

What exactly is not working? 到底什么不起作用? Does the button not appear, does it not function? 该按钮没有出现吗,不起作用?

I would suggest using something like the following: 我建议使用类似以下的内容:

var myAudio = document.getElementById("myAudio");
var isPlaying = false;

function togglePlay() {
  if (isPlaying) {
    myAudio.pause()
  } else {
    myAudio.play();
  }
};
myAudio.onplaying = function() {
  isPlaying = true;
};
myAudio.onpause = function() {
  isPlaying = false;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM