Enhancing audio control features using HTML and JavaScript

After utilizing various suggestions, I have successfully created a basic audio slider that starts playing sound (at zero volume) when clicked by the user. They can then adjust the volume as needed.

My only challenge is that the volume adjustment only occurs once the user releases the mouse after moving the slider, rather than changing gradually as they drag it. Is there a way to achieve smooth volume adjustments while moving the slider? Any assistance would be greatly appreciated.

JS

var mediaClip;
var volume1;

function init()
{
    mediaClip = document.getElementById("mediaClip");
    volume1 = document.getElementById("volume1");

    mediaClip.play();
}

function setVolume() {
    var mediaClip = document.getElementById("mediaClip");
    mediaClip.volume = document.getElementById("volume1").value;
}


function play() {
    var audio = document.getElementById("mediaClip");
    audio.play();
}

HTML

<body onload="init()">
    <audio id="mediaClip" src="A Very Brady Special.mp3"  style="display:none" allow="autoplay" controls>
        <p>Your browser does not support the audio element</p>
    </audio>

    <input type="range" onchange="setVolume()" id='volume1' min=0 max=1 step=0.01 value='0' onclick="play()">
</body>

Answer №1

Here's a simple solution:

<input type="range" oninput="setVolume()" id='volume1' min=0 max=1 step=0.01 value='0' onclick="play()">

Just use the above code snippet instead of this:

<input type="range" onchange="setVolume()" id='volume1' min=0 max=1 step=0.01 value='0' onclick="play()">

Answer №2

To improve the functionality, as connexo pointed out, it's better to use oninput instead of onchange. Additionally, utilizing setVolume(this) allows for a cleaner and more versatile approach that can be applied to any slider.

var mediaClip;
var volume1;

function initialize() {
  mediaClip = document.getElementById("mediaClip");
  volume1 = document.getElementById("volume1");

  mediaClip.play();
}

function adjustVolume(element) {
  var newValue = element.value;
  
  document.getElementById("volumeVal").innerHTML = newValue;
  mediaClip.volume = newValue;
}


function playMedia() {
  var audio = document.getElementById("mediaClip");
  audio.play();
}
<body onload="initialize()">

  <audio id="mediaClip" src="A Very Brady Special.mp3" style="display:none" allow="autoplay" controls>
    <p>Your browser does not support the audio element</p>
  </audio>

  <p>onChange</p>
  <input type="range" onchange="adjustVolume(this)" id='volume1' min=0 max=1 step=0.01 value='0' onclick="playMedia()">
  
  <p>onInput</p>
  <input type="range" oninput="adjustVolume(this)" id='volume1' min=0 max=1 step=0.01 value='0' onclick="playMedia()">
  
  <h3>Volume: <span id="volumeVal">0</span></h3>

</body>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging the power of Ajax in JavaScript

For my assignment, I successfully made two separate paragraphs hide and show using jQuery. Moving forward, the next step involves integrating JavaScript Ajax code to allow the paragraphs to toggle visibility. To achieve this, I created two distinct HTML fi ...

replace specific elements for cloze deletion evaluation

Consider this scenario: There are many reasons to succeed. (consisting of more than 5 words) phrases = ['There', 'are', 'many', 'reasons', 'to', 'succeed'] flashcards_count = ceil(len(phrase) / 3 ...

Inconsistencies with AJAX performance

Hey there, I'm a newbie and absolutely loving this site! Currently diving into the world of JavaScript and have been through numerous tutorials. However, I seem to be struggling with getting Ajax to work. Recently stumbled upon this code snippet on ...

Take the user input from the form and incorporate it into the URL for the AJAX request

How can I dynamically update the URL in the AJAX call asynchronously? I've made a few attempts, but none of them seem to work. This is the current code: <!-- Input form --> <form class="navbar-form navbar-left" role="search" id="formversion" ...

Aligning thumbnail images in a jQuery Mobile listview

Hey, I recently added a list view that includes thumbnails. I used the following code: <ul data-role="listview" data-inset="false" data-theme="a" data-dividertheme="d> <li><a href="image.php?imgid=2"> <img src="../images/comma. ...

After the rendering process, the React Component member goes back to a state of

One issue I encountered is related to a component that utilizes a separate client for making HTTP requests. Specifically, when trying to use the client within a click event handler, the call to this.client.getChannel() fails due to this.client being undefi ...

Eliminate the header top margin in Bootstrap

HTML <div class="container-fluid"> <div class="row"> <div class="page-header header_site"> <h1><font>ABC Company</font></h1> </div> </div> </div> CSS Code: .header_site { b ...

The functionality of passing POST variables to the model seems to be malfunctioning in PHP CodeIgniter when attempting to use the

I attempted the code snippet below: function doAjax() { var sList = ""; $('input[type=checkbox]').each(function () { var sThisVal = (this.checked ? "1" : "0"); ...

JavaScript Linked List Operations: Issues with the removeHead() and contains() Functions

Incorporating ES6 syntax, the challenge is to construct a linked list and subject it to an npm linter test. Below is the code implementation: class LinkedList { constructor() { this.head = null; this.tail = null; // Do not alter anything wit ...

Issue with external variable not being updated properly in success callback

Working through an array of data, I make updates to a variable called commentBody during each iteration. However, even though the variable is modified within the loop itself, whenever I try to access it from inside a success callback, it consistently show ...

Error: Uncaught promise rejection - The function is undefined in the context of Vue.js and Electron

I've been experimenting with anime.js to animate elements using promise functions. However, I'm encountering an issue where the second function does not run after the previous one successfully completes. <script> import Splash from '. ...

What is the difference in speed between drawing on a transparent canvas and determining if a point is transparent compared to determining if a point is within a complex polygon?

I'm curious if anyone has done research on adding event support to a game engine. Specifically, I am working on incorporating pixel-perfect hover over 2D object event support into my own game engine. I am exploring different ways of achieving this eff ...

Activate audio and trigger notification

I'm looking to incorporate a small beep sound into my web application before displaying an alert message. Here's what I currently have: if(_none_valid) { $.playSound('/static/wav/beep_error.wav').delay(300); alert('ERROR: ...

What could be causing the error when attempting to release this Node-MySQL pool?

My first attempt at utilizing connection pooling is with Node.js. I crafted a database connection module in Node.js to establish a single connection, which is then referenced within a pooling function for later use when passed to different modules. /* D ...

Retrieve the text input from the text field and display it as

Is there a way to display what users enter in a textfield when their accounts are not "Activated"? Here's an example: if(active == NULL);{ //I've attempted the following methods. //In this scenario, 'username' is the name of ...

The express gateway is unable to transfer multipart/formdata

I've implemented express gateway as my main service gateway. One of the services I have needs to update an image, and when I try to handle files independently using multer it works fine. However, once this service is routed through express gateway, th ...

Populate an AngularJS select dropdown with JSON data and automatically pre-select the specified value

I am currently dealing with 2 entities: project and project_types. Each project can have one or multiple project_types associated with it. Using ajax (ng-init), I am retrieving the project data (including its related project_types) and all available proje ...

Incorrect Request Method for WCF json POST Request Leads to 405 Error (Method Not Allowed)

Hey there, I'm facing an issue with using Microsoft Visual Studio to create a WCF web service. Everything runs smoothly within Visual Studio, but when I try to connect to the service from outside, it fails to establish a connection. At first, I encoun ...

Tips for modifying the color of the last anchor in a list item

li elements are utilized to create breadcrumb in a shopping cart. The breadcrumb displays all anchor elements using the style defined for an 'a' element from site.css. How can I make the last anchor's color black? I attempted the style belo ...

The transformation of all relative URLs into absolute URLs is carried out

The issue at hand seems to be peculiar to Chrome and Firefox, as IE does not exhibit the same behavior. In my angular application, I've noticed a strange phenomenon. Once a specific view is loaded, all XHR requests made using relative paths are autom ...