是否可以有一个可以切换音频播放状态的按钮

时间:2016-11-07 21:51:34

标签: javascript html

我正在创建一个网页,我希望人们能够按下键盘上的按钮来播放声音,我已经通过谷歌搜索了一下这部分工作。现在我想在页面上打开/关闭开关,可以关闭键盘按下的声音,这样那些不想要按键发出声音的人可以选择这个,这可能吗?

现在,每当按下按钮时,我都会使用此JavaScript和HTML播放声音(在此示例中为A):

JavaScript的:

$(document).keydown(function(e){
    if (e.keyCode == 65) { 
        document.getElementById('A').play();
        return false;
    }
});

HTML:

<audio id="A" src="A.ogg"></audio>

3 个答案:

答案 0 :(得分:2)

只需设置一个布尔标志来跟踪播放状态并检查标志以执行正确的操作:

这是长版:

var playing = false;
var playsound = function(e){
    if (e.keyCode === 65 && !playing) { 
        document.getElementById('A').play();
        playing = true;
        return false;
    } else if(e.keyCode === 65 && playing){
        document.getElementById('A').pause();
        playing = false;
        return false;
    }
}

或者,更简洁的版本:

&#13;
&#13;
var playing = false;
var a = document.getElementById('A');

document.addEventListener("keydown", function(e){
    if (e.keyCode === 65){
       (!playing) ? a.play() : a.pause();
       playing = !playing;
       console.log("Sound is: " + playing);
       return false;
    }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<audio id="A" src="" controls></audio>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以删除侦听器并在按钮上重新添加

var playsound = function(e){
    if (e.keyCode == 65) { 
        document.getElementById('A').play();
        return false;
    }
}
var soundEnabled = true;

$("body").on("keydown", playsound);

$(#button).click(function(){
  soundEnabled = !soundEnabled;
  if(soundEnabled){
    $("body").on("keydown", playsound);
  }else{
    $("body").off("keydown", playsound);
  }
});

答案 2 :(得分:0)

我在google上找到了我能想象到的一切后终于找到了解决方案,最后我找到了this回答了别人在这个网站上提出的另一个问题!所以我就是这样做的答案:

HTML

<audio id="A" src="A.ogg"></audio>

<button onclick="document.getElementById('A').muted=!document.getElementById('A').muted">Mute/ Unmute</button>

的Javascript

$(document).keydown(function(e){
    if (e.keyCode == 65) { 
        document.getElementById('A').play();
        return false;
    }
});

因此,使用这种方法,我根本不需要更改Javascript,它仍然完全符合我的要求!

感谢所有试图提供帮助的人,但由于这是我第一次使用javascript,我不明白我应该如何处理你的答案。我发现这个答案对我来说也很有意义,因为我至少知道HTML如何工作......但是,不管怎样,谢谢!