我想通过JavaScript控制音量。

我发现了如何控制音频对象。
但是,我不知道如何控制音量设置。

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

最佳答案

这是一些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>

关于javascript - 如何通过JavaScript控制浏览器的音量?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29205255/

10-11 22:40
查看更多