简体   繁体   English

如何设置特定的起始音量 <audio> 标签

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

I only have basic knowledge of HTML and CSS and have looked through Google extensively trying to find an answer to this question -- it all seems to point to JavaScript and/or jQuery. 我只掌握HTML和CSS的基本知识,并通过谷歌广泛试图找到这个问题的答案 - 这一切似乎都指向JavaScript和/或jQuery。 I tried it, and I can't get it to work. 我试过了,我无法让它发挥作用。

I have an audio file that starts to play when my website loads. 我有一个音频文件,当我的网站加载时开始播放。 I want to set a specific starting volume so that my visitors don't get a heart attack if their volume is high. 我想设置一个特定的起始音量,以便我的访客在音量很高时不会心脏病发作。

This is what I have: 这就是我所拥有的:

HTML: HTML:

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

CSS: CSS:

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

JavaScript: JavaScript的:

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

Any help would be greatly appreciated! 任何帮助将不胜感激!

You're not getting the element, and the error shows up in the console 您没有获得该元素,并且错误显示在控制台中

Cannot set property 'volume' of null 无法将属性'volume'设置为null

Move the script to right before the </body> tag, or do : 将脚本移到</body>标记之前,或执行以下操作:

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

EDIT: 编辑:

Nothing is more annoying than disabling right clicks, but anyway, here's what you have 没有什么比禁用右键点击更烦人了,但无论如何,这就是你拥有的

;(function($){
mySong=document.getElementById("bgAudio");
mySong.volume=0.2;

setVolume = function(bgAudio,vol) {
    sounds[bgAudio].volume = 0.33;
}
})(jQuery);

now change it to 现在改成它

jQuery(function($) {
    $("#bgAudio").prop("volume", 0.2);

    window.setVolume = function(bgAudio, vol) {
        sounds[bgAudio].volume = vol;
    }
});

Use JavaScript to set the volume, however you need to make sure to have the DOM ready to modify any objects. 使用JavaScript设置卷,但是您需要确保DOM准备好修改任何对象。 Perhaps use an ondocumentready event, or a Click event from a call-to-action. 也许使用ondocumentready事件或来自号召性用语的Click事件。

First, get the video object you want to modify. 首先,获取要修改的视频对象。

bgAudio = document.getElementById("bgAudio");

Then use the bgAudio object to set its properties, like the volume. 然后使用bgAudio对象设置其属性,如卷。

bgAudio.volume = 0.2;

Since you are working on a website, I would do something like this (assuming you can use jQuery): 既然你在网站上工作,我会做这样的事情(假设你可以使用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();
});

Check out this reference material on jquery ready, events and videos: 查看有关jquery ready,事件和视频的参考资料:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM