{"id":358,"date":"2024-01-08T05:59:42","date_gmt":"2024-01-08T00:29:42","guid":{"rendered":"http:\/\/codetheory.in\/?p=358---7fce1f1b-00c2-4e9b-b282-8cf90cb1413d"},"modified":"2024-01-08T05:59:42","modified_gmt":"2024-01-08T00:29:42","slug":"controlling-the-volume-of-an-audio-file-in-javascript","status":"publish","type":"post","link":"https:\/\/codetheory.in\/controlling-the-volume-of-an-audio-file-in-javascript\/","title":{"rendered":"Controlling the Volume of an Audio File in Javascript"},"content":{"rendered":"

Just another quick tip. I’ll show you how to change the volume of an audio file of whatever format you are using – mp3, ogg, wav, aac, etc.
\n<\/p>\n

When Using the HTML5 <audio> Element<\/h2>\n

If you are using the audio<\/code> tags, just get the DOM Node in Javascript and manipulate the volume<\/code> property.<\/p>\n

\r\nvar audio = document.querySelector('audio');\r\n\/\/ Getting\r\nconsole.log(volume); \/\/ 1\r\n\/\/ Setting\r\naudio.volume = 0.5; \/\/ Reduce the Volume by Half\r\n<\/pre>\n

The number that you set should be in the range 0.0<\/code> to 1.0<\/code>, where 0.0<\/code> is the quietest and 1.0<\/code> is the loudest.<\/p>\n

Note: If the value you set is not in the range 0.0<\/code> to 1.0<\/code>, then JS will throw an IndexSizeError<\/code>.<\/p>\n

Web Audio API<\/h2>\n

A bit of code first, where we’ll load our music file and play it using the Web Audio API.<\/p>\n

\r\nvar ctx = new webkitAudioContext();\r\n\r\nfunction loadMusic(url) {\r\n  var req = new XMLHttpRequest();\r\n  req.open('GET', url, true);\r\n  req.responseType = 'arraybuffer';\r\n\r\n  req.onload = function() {\r\n    ctx.decodeAudioData(req.response, playSound);\r\n  };\r\n\r\n  req.send();\r\n}\r\n\r\nfunction playSound(buffer) {\r\n  var src = ctx.createBufferSource();\r\n  src.buffer = buffer;\r\n  src.connect(ctx.destination);\r\n  \/\/ Play now!\r\n  src.noteOn(0);\r\n}\r\n<\/pre>\n

So, we load the audio file using XHR2<\/code> and then decode that to PCM Audio Data. In playSound<\/code> we create a Source, set its buffer to the AudioBuffer<\/code> object and connect it to the Destination (Speakers, Headphones, etc.). After the connection we finally play it. The entire flow is something like this:<\/p>\n

Source<\/strong> -> Destination<\/strong><\/p>\n

If we want to control the volume of the audio, we need to connect the Source to a GainNode<\/code> which in turn will be conntected to the Destination. The flow will be like this then:<\/p>\n

Source<\/strong> -> GainNode<\/strong> -> Destination<\/strong><\/p>\n

The code will be something like this:<\/p>\n

\r\nfunction playSound(buffer) {\r\n  var src = ctx.createBufferSource();\r\n  src.buffer = buffer;\r\n\r\n  var gain_node = ctx.createGainNode();\r\n  src.connect(gain_node);\r\n\r\n  \/\/ ATTENTION! We're connecting the gain_node (NOT the source)\r\n  \/\/ to the destination\r\n  gain_node.connect(ctx.destination);\r\n\r\n  \/\/ Changing the Volume\r\n  gain_node.gain.value = 1;\r\n\r\n  src.noteOn(0);\r\n}\r\n<\/pre>\n

Nice! The gain_node<\/code> object has a property called gain<\/code> which in turn has a property called value<\/code>. Now, Controlling the volume is just a matter of changing the value of gain_node.gain.value<\/code>. You can set a negative value (less than 0<\/code>) or more than 1<\/code> if you’d like to. Higher values will not throw exceptions unlike the other case that we covered with the <audio><\/code> element.<\/p>\n

\"\"<\/a><\/p>\n

Note: noteOn()<\/code> has been changed to start()<\/code> recently in the specs.<\/p>\n

Using an Input Range Slider<\/h2>\n

Hell yeah! You can use an input[type=\"range\"]<\/code> for better controls and change the volume of the audio! Quite simple, as you can already imagine. Just attach an onchange<\/code> event handler to the input range and alter the gain_node.gain.value<\/code>.<\/p>\n

\r\ndocument\r\n  .querySelector('#input_range_id')\r\n  .addEventListener('change', function() {\r\n\r\n  gain_node.gain.value = this.value;\r\n\r\n}, false);\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"

Just another quick tip. I’ll show you how to change the volume of an audio file of whatever format you are using – mp3, ogg, wav, aac, etc.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[40],"tags":[43,8,45],"_links":{"self":[{"href":"https:\/\/codetheory.in\/wp-json\/wp\/v2\/posts\/358"}],"collection":[{"href":"https:\/\/codetheory.in\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codetheory.in\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codetheory.in\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codetheory.in\/wp-json\/wp\/v2\/comments?post=358"}],"version-history":[{"count":16,"href":"https:\/\/codetheory.in\/wp-json\/wp\/v2\/posts\/358\/revisions"}],"predecessor-version":[{"id":1890,"href":"https:\/\/codetheory.in\/wp-json\/wp\/v2\/posts\/358\/revisions\/1890"}],"wp:attachment":[{"href":"https:\/\/codetheory.in\/wp-json\/wp\/v2\/media?parent=358"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codetheory.in\/wp-json\/wp\/v2\/categories?post=358"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codetheory.in\/wp-json\/wp\/v2\/tags?post=358"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}