【问题标题】:is it possible to make only one volume control for multiple audio是否可以只对多个音频进行一个音量控制
【发布时间】:2022-02-07 00:10:49
【问题描述】:

我正在开发一个供个人使用的交互式视频网站项目。这里我想一次对多个音频进行一个音量控制,我该怎么做?

我尝试为一个音频设置一个音量控制,并且成功了:

var audio = document.getElementById('bgsound1');
var volumeControl = document.getElementById('vol-control');

var setVolume = function(){
audio.volume = this.value / 100;
};

volumeControl.addEventListener('change',setVolume);
volumeControl.addEventListener('input',setVolume);

这里是我的音频标签:

<audio src="asset/sound/M2.mp3" id="bgsound1"></audio>
<audio src="asset/sound/sound2.mp3" id="bgsound2"></audio>
<audio src="asset/sound/sound3.mp3" id="bgsound3"></audio>

【问题讨论】:

    标签: javascript html audio volume


    【解决方案1】:

    当然,您必须遍历每个音频元素。请参阅下面代码中的 cmets。

    let volumeControl = document.getElementById('vol-control');
    
    function setVolume (){
    
      console.clear()
      console.log(volumeControl.value)
      
      // Get the array of audio element and loop through them to set the new volume value
      Array.from(document.querySelectorAll("audio")).forEach(function(audio){
      
          //  if the input value is "", use zero
          audio.volume = volumeControl.value == "" ? 0 : volumeControl.value / 100;
        })
    };
    
    volumeControl.addEventListener('change', setVolume);
    volumeControl.addEventListener('input', setVolume);
    
    // On load
    setVolume()
    <input id="vol-control" type="number" min="0" max="100" value="25">
    <br>
    
    
    <audio src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3" id="bgsound1" controls></audio>
    <audio src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-8.mp3" id="bgsound2" controls></audio>
    <audio src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-16.mp3" id="bgsound3" controls></audio>

    【讨论】:

    • 谢谢,这很有帮助。我几乎绝望了,将在我的网站上删除此音量功能。因为我刚学javascript。
    猜你喜欢
    • 2020-10-25
    • 1970-01-01
    • 1970-01-01
    • 2015-11-06
    • 1970-01-01
    • 2012-10-17
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多