简体   繁体   中英

How to set volume of audio file in JavaScript

I can't seem to adjust the volume on this audio element i have when loading the page. here is the code

    var bleep = new Audio();
    bleep.src = "Projectwebcrow2.mp3";
    bleep.volume = 0.1;

If you are using the audio tags, just get the DOM Node in Javascript and manipulate the volume property.

var audio = document.querySelector('audio');
// Getting
console.log(volume); // 1
// Setting
audio.volume = 0.5; // Reduce the Volume by Half

The number that you set should be in the range 0.0 to 1.0, where 0.0 is the quietest and 1.0 is the loudest. Note: If the value you set is not in the range 0.0 to 1.0, then JS will throw an IndexSizeError.

FOR WEB AUDIO API, A bit of code first, where we'll load our music file and play it using the Web Audio API.

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);
}

It should work. You need to give us more details(I can't comment). If you didn't already, just add

bleep.play()

Also, autoplaying audio is disabled by default in most browsers, maybe that is the cause.

If your music is an element from the page, you can use:

var music = document.getElementById("myMusic");
music.volume = 0.2;

If it isn't, use:

var music = new Audio('audio/correct.mp3');
music.volume = 0.2;

You can check https://www.w3schools.com/tags/av_prop_volume.asp

For more details

Ok..I was going to suggest you create a function for it and call the function. Since it has worked out, best of luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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