[英]How to set volume of audio file in JavaScript
加载页面时,我似乎无法调整此音频元素的音量。 这是代码
var bleep = new Audio();
bleep.src = "Projectwebcrow2.mp3";
bleep.volume = 0.1;
如果您使用音频标签,只需获取 Javascript 中的 DOM 节点并操作音量属性。
var audio = document.querySelector('audio');
// Getting
console.log(volume); // 1
// Setting
audio.volume = 0.5; // Reduce the Volume by Half
您设置的数字应在 0.0 到 1.0 的范围内,其中 0.0 是最安静的,1.0 是最响亮的。 注意:如果你设置的值不在 0.0 到 1.0 的范围内,那么 JS 会抛出一个 IndexSizeError。
对于 WEB AUDIO API,首先编写一段代码,我们将在其中加载我们的音乐文件并使用 Web3A8DE14634 播放音乐文件。
var ctx = new webkitAudioContext();
function loadMusic(url) {
var req = new XMLHttpRequest();
req.open('GET', url, true);
req.responseType = 'arraybuffer';
req.onload = function() {
ctx.decodeAudioData(req.response, playSound);
};
req.send();
}
function playSound(buffer) {
var src = ctx.createBufferSource();
src.buffer = buffer;
src.connect(ctx.destination);
// Play now!
src.noteOn(0);
}
它应该工作。 你需要给我们更多的细节(我不能评论)。 如果您还没有,只需添加
bleep.play()
此外,大多数浏览器默认禁用自动播放音频,也许这就是原因。
如果您的音乐是页面中的一个元素,您可以使用:
var music = document.getElementById("myMusic");
music.volume = 0.2;
如果不是,请使用:
var music = new Audio('audio/correct.mp3');
music.volume = 0.2;
您可以查看https://www.w3schools.com/tags/av_prop_volume.asp
更多细节
好的..我会建议你为它创建一个 function 并调用 function。 既然已经成功了,祝你好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.