如何为<音频>标签

How to set a specific starting volume for <audio> tag

本文关键字:音频 gt 标签 lt      更新时间:2023-09-26

我对HTML和CSS只有基本的了解,并在谷歌上进行了广泛的搜索,试图找到这个问题的答案——这一切似乎都指向JavaScript和/或jQuery。我试过了,但我无法让它发挥作用。

我有一个音频文件,当我的网站加载时开始播放。我想设定一个特定的开始音量,这样我的访客在音量高时就不会心脏病发作。

这就是我所拥有的:

HTML:

<audio id="bgAudio" autoplay="autoplay" controls="controls" loop="loop" src="audio/025.mp3"></audio>

CSS:

#bgAudio {
position:fixed;
z-index:1000; 
width:250px;
}

JavaScript:

backgroundAudio=document.getElementById("bgAudio");
backgroundAudio.volume=0.5;

如有任何帮助,我们将不胜感激!

您没有得到元素,错误显示在控制台中

无法设置空的属性"volume"

将脚本移到</body>标记的正前方,或者执行:

window.onload = function() {
    var backgroundAudio=document.getElementById("bgAudio");
    backgroundAudio.volume=0.5;
}

编辑:

没有什么比禁用右键点击更烦人的了,但无论如何,以下是你的

;(function($){
mySong=document.getElementById("bgAudio");
mySong.volume=0.2;
setVolume = function(bgAudio,vol) {
    sounds[bgAudio].volume = 0.33;
}
})(jQuery);

现在将其更改为

jQuery(function($) {
    $("#bgAudio").prop("volume", 0.2);
    window.setVolume = function(bgAudio, vol) {
        sounds[bgAudio].volume = vol;
    }
});

使用JavaScript设置卷,但需要确保DOM已准备好修改任何对象。也许可以使用ondocumentready事件,或者操作调用中的Click事件。

首先,获取要修改的视频对象。

bgAudio = document.getElementById("bgAudio");

然后使用bgAudio对象设置其属性,如音量。

bgAudio.volume = 0.2;

既然你在一个网站上工作,我会做这样的事情(假设你可以使用jQuery):

$(document).ready(function() {
    // the site has now loaded, grab the video!
    bgAudio = document.getElementById("bgAudio");
    // now tweak the volume!
    bgAudio.volume = 0.2;
    // now, play it!
    bgAudio.play();
});

查看jquery ready上的参考资料,事件和视频:

  • http://api.jquery.com/ready/
  • https://developer.mozilla.org/en-US/docs/Web/Reference/Events
  • https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video