如何通过JavaScript控制浏览器的卷?

时间:2015-03-23 07:41:09

标签: javascript audio volume

我想通过JavaScript控制音量。

我找到了如何控制Audio对象。 但是,我不知道如何控制音量设置。

你能告诉我如何通过JavaScript或一些好的模块来控制音量吗?

2 个答案:

答案 0 :(得分:3)

这里有一些javascript,它为浏览器提供了一个窗口小部件,可以在渲染音频时更改音量...只需在下面更新并使用一些音频文件(mp3)填充变量audio_url,您可以将其放入相同的目录中,如下面的代码

<html>
<head>
    <title>render audio with volume control</title>
</head>

<body>

    <p>Volume</p>
    <input id="volume" type="range" min="0" max="1" step="0.1" value="0.5"/>

    <script>

    var audio_context = null;
    var gain_node = null;

    window.AudioContext = window.AudioContext || window.webkitAudioContext;
    audio_context = new AudioContext();

    gain_node = audio_context.createGain(); // Declare gain node
    gain_node.connect(audio_context.destination); // Connect gain node to speakers




    function render_audio() {

        var request = new XMLHttpRequest();

        var audio_url = "your_music.mp3";

        request.open('GET', audio_url, true); // loading local file for now
        request.responseType = 'arraybuffer';

        // Decode asynchronously
        request.onload = function() {

            audio_context.decodeAudioData(request.response, function(buffer) {

                stored_buffer = buffer; // store buffer for replay later

                var source = audio_context.createBufferSource(); // creates a sound source
                source.buffer = buffer;                    // tell the source which sound to play
                source.connect(gain_node);       // connect source to speakers
                source.start(0);                           // play the source now
            });
        };
        request.send();
    }

    // --- enable volume control for output speakers

    document.getElementById('volume').addEventListener('change', function() {

      var curr_volume = this.value;
      gain_node.gain.value = curr_volume;

      console.log("curr_volume ", curr_volume);
    });


    // init
    render_audio();

    </script>

      <body onkeypress="render_audio()">

    <button onclick="render_audio()">play_again</button>

</body>
</html>

答案 1 :(得分:1)

以下控制音量的示例来自Mozilla的“使用HTML5音频和视频指南”:

https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_HTML5_audio_and_video

<audio id="demo" src="audio.mp3"></audio>
<div>
  <button onclick="document.getElementById('demo').play()">Play the Audio</button>
  <button onclick="document.getElementById('demo').pause()">Pause the Audio</button>
  <button onclick="document.getElementById('demo').volume+=0.1">Increase Volume</button>
  <button onclick="document.getElementById('demo').volume-=0.1">Decrease Volume</button>
</div>

如果您要访问系统卷,那么答案是JavaScript无法做到这一点。这在前面已经讨论过:

Javascript: Can you read the systems volume?