音频暂停/播放

时间:2015-05-23 16:44:18

标签: jquery html audio

我不知道我做错了什么

<script>
$(document).ready(function() {
    var playing = false;
    var audioElement = document.createElement('audio');
    audioElement.setAttribute('src', 'star.mp3');
    $('#star').click(function() {
    playing == true;
    if(playing == true) audioElement.pause();
    else audioElement.play();
    });
});

它的意思是当播放一个声音并且我点击另一个声音时,已经播放的声音应该停止而另一个声音应该开始。

1 个答案:

答案 0 :(得分:1)

我认为你的问题在这里:

$('#star').click(function() {
    playing == true; // should be = not == if you're trying to assign 
    if(playing == true) audioElement.pause(); // but if you assign then playing is always true
    else audioElement.play();
    });

assignment operators
comparison operators

这是一个可能有帮助的简化版本:

$(document).ready(function() {
  var audio1 = $("#DunDunDun")[0];
  var audio2 = $("#WaWaWaa")[0];
  $("#ominousMusic").click(function() {
    audio1.play();
    audio2.pause();
  });
  $("#sadMusic").click(function() {
    audio2.play();
    audio1.pause()
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ominousMusic" title="go on, click it, you know you want to...">
  cue ominous music...
</div>
<audio id="DunDunDun">
  <source src="http://pluggedinwebdesign.com/media/DunDunDun.mp3">
    Your browser isn't invited to super fun audio time.
</audio>
<div id="sadMusic" title="go on, click it, you know you want to...">
  cue sad music...
</div>
<audio id="WaWaWaa">
  <source src="http://pluggedinwebdesign.com/media/Sad_Trombone.mp3">
    Your browser isn't invited to super fun audio time.
</audio>