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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:23:16  来源:igfitidea点击:

Lower background music volume when autoplay HTML

javascripthtml

提问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 setHalfVolumefunction. 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 playon 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 resetVolumeand setHalfVolumeare declared sort of like:

在哪里resetVolumesetHalfVolume被声明有点像:

function setHalfVolume() { 
    document.getElementById("audio1").volume /= 2;
}
function resetVolume() { 
    document.getElementById("audio1").volume *= 2;
}