【问题标题】:Starting/Stopping sound with javascript onClick使用 javascript onClick 启动/停止声音
【发布时间】:2017-09-29 22:52:23
【问题描述】:

这是我的第一篇文章,我已经搜索了一些答案,但没有遇到任何解决方案。

基本上我想做的就是使用 javascript 函数 playSound(sound) 使 onClick="" 开始和停止音频。到目前为止,这是我结束的内容。现在,当我单击时没有音频播放,但是当我单独测试单个代码“song1.play()”时,声音会播放,但再次单击时显然不会停止。希望这不会太难。

function playSound(sound){
        var song1=document.getElementById(sound);
        var isPlaying = true;
        if (!isPlaying){
            isPlaying == true;
            song1.play();
        } 
        else{
            isPlaying == false;
            song1.pause();
        }
    }

【问题讨论】:

    标签: javascript jquery html audio onclick


    【解决方案1】:

    两个小的更正。

    a) var isPlaying = true; 应在全局声明,以在多次调用“OnClick”之间保留其值。

    b) `isPlaying' 变量的赋值语句中的== 应更改为=

    var isPlaying = true;
     function playSound(sound){
                var song1=document.getElementById(sound);
                if (!isPlaying){
                    isPlaying = true;
                    song1.play();
                } 
                else{
                    isPlaying = false;
                    song1.pause();
                }
            }
    

    【讨论】:

      【解决方案2】:

      您将 isPlaying 变量与 true 和 false 进行比较,而不是将它们分配给变量。现在应该可以了。

      function playSound(sound){
          var song1=document.getElementById(sound);
          var isPlaying = true;
          if (!isPlaying){
              isPlaying = true;
              song1.play();
          } 
          else{
              isPlaying = false;
              song1.pause();
          }
      }
      

      【讨论】:

        【解决方案3】:

        你应该使用 = 而不是 ==

        = 是赋值运算符,其中 == 是比较运算符。

        【讨论】:

          【解决方案4】:

          您可以使用paused 属性检查声音是否暂停:

          function playSound(sound) {
            var song1 = document.getElementById(sound);
            song1.volume = .25; // setting the volume to 25% because the sound is loud
            if (song1.paused) {  // if song1 is paused
              song1.play();
            } else {
              song1.pause();
            }
          }
          <audio id="sound">
            <source src="https://www.w3schools.com/TagS/horse.mp3" type="audio/mp3">
          </audio>
          <button onclick="playSound('sound')">Play/Pause</button>

          【讨论】:

          • 嗨,谢谢。事实证明,在 html 中编写脚本只会使某些事情不起作用。我把它放在一个单独的 js 文件中并将它链接到 html 并且它工作得很好,谢谢。
          猜你喜欢
          • 2011-08-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-11-07
          • 2011-06-23
          • 1970-01-01
          相关资源
          最近更新 更多