javascript 自动播放 HTML 时降低背景音乐音量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20390421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Lower background music volume when autoplay HTML
提问by Coding hierarchy
I have a page that has some animal images and when you click on them it plays the sound of the animal, but since its a kid's game I have a background music, but the sound is too loud. I want when the background music plays automatically, the volume changes to 0.5. How can I set a function that does that? I don't want a function based on click, I want it hidden and change the volume automatically.
我有一个页面有一些动物图像,当你点击它们时,它会播放动物的声音,但由于它是儿童游戏,我有背景音乐,但声音太大了。我想当背景音乐自动播放时,音量更改为 0.5。我怎样才能设置一个功能呢?我不想要基于点击的功能,我想要它隐藏并自动更改音量。
The function (it's not working)
功能(它不起作用)
myAudio = document.getElementById("audio1");
function setHalfVolume() {
myAudio.volume = 0.4;
}
HTML
HTML
<audio id= "audio1" controls="controls" onload="setHalfVolume()">
<source src="Audio\Jaunty Gumption.mp3" type="audio/mp3">
</audio>
回答by PhearOfRayne
The event you need is called onloadeddata.
您需要的事件称为onloadeddata。
Also unless you need access to the myAudio variable from other functions or globally I would suggest moving it into the setHalfVolume
function. Give this a try.
此外,除非您需要从其他函数或全局访问 myAudio 变量,否则我建议将其移动到setHalfVolume
函数中。试试这个。
Change your HTML to:
将您的 HTML 更改为:
<audio id= "audio1" controls="controls" onloadeddata="setHalfVolume()">
<source src="Audio\Jaunty Gumption.mp3" type="audio/mp3">
</audio>
Change your JavaScript to:
将您的 JavaScript 更改为:
function setHalfVolume() {
var myAudio = document.getElementById("audio1");
myAudio.volume = 0.5; //Changed this to 0.5 or 50% volume since the function is called Set Half Volume ;)
}
回答by megawac
Try adding an event for play
on all of the audio elements of interest and calling setHalfVolume in there:
尝试为play
所有感兴趣的音频元素添加一个事件,并在其中调用 setHalfVolume:
document.querySelector('#audio1').addEventListener('play', setHalfVolume);
You'll also probably want to reset the volume back to normal after
您可能还想在之后将音量重置为正常
document.querySelector('#audio1').addEventListener('pause', resetVolume);
Where resetVolume
and setHalfVolume
are declared sort of like:
在哪里resetVolume
和setHalfVolume
被声明有点像:
function setHalfVolume() {
document.getElementById("audio1").volume /= 2;
}
function resetVolume() {
document.getElementById("audio1").volume *= 2;
}