使用javascript使用向上和向下箭头控制音量

时间:2016-05-26 11:32:26

标签: javascript jquery audio

使用下面的javascript,我可以使用空格键播放和暂停音频,并使用左右箭头前后移动,但现在我需要使用向上和向下箭头增加和减少音量,当我点击它应该去启动音频文件,当我点击结束按钮它应该到音频文件的结尾。我可以这样做

 <script>
            var audio = $("audio")[0];
            $(document).keydown(function (e) {
                var unicode = e.charCode ? e.charCode : e.keyCode;
                console.log(unicode);
                // right arrow
                if (unicode == 39) {
                    audio.currentTime += 5;
                    // back arrow
                } else if (unicode == 37) {
                    audio.currentTime -= 5;
                    // spacebar
                } else if (unicode == 32) {
                    if (audio.paused) {
                        audio.play();
                    }
                    else {
                        audio.pause()
                    }
                }
            });
    </script>

1 个答案:

答案 0 :(得分:0)

对于音量,你应该试试这个:

var audio = $("audio")[0];
var source = audioCtx.createMediaElementSource(audio);
var gainNode = audioCtx.createGain();

$(document).keydown(function(e) {
  var keycode = e.which;

  if (keycode == 39) { // right arrow
    audio.currentTime += 5;
  } else if (keycode == 37) { // left arrow
    audio.currentTime -= 5;
  } else if (keycode == 38) { // up arrow
    gainNode.gain.value += 0.1;
  } else if (keycode == 40) { // down arrow
    gainNode.gain.value -= 0.1;
  } else if (keycode == 32) { // spacebar
    if (audio.paused) {
      audio.play();
    } else {
      audio.pause()
    }
  }
});