0

I'm in my first week of learning how to code and running into some trouble with HTML5 audio on how to connect a slider to the volume.

My code is below and any suggestions are appreciated. The main part I'm unsure about is my script for setVolume(); I'm just having trouble getting my head around it.

<!DOCTYPE html>
 <head>
    <title>Slider + Play/Pause</title>

    <script>
        "use strict";
        /*function playMusic() {
           document.getElementById("mediaClip").play();
       }*/
var mediaClip = document.getElementbyId("mediaClip");
    var volume1 = document.getElementbyId("volume1");

function playPause() {
    var mediaClip = document.getElementById("mediaClip");
    if (mediaClip.paused) {
        mediaClip.play();   
    } else {
        mediaClip.pause();
    }
}

function change() {
    var button1 = document.getElementById("button1");
    if (button1.value==="Play") button1.value = "Pause";
    else button1.value = "Play";
}

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

}
    </script>      
</head>
<body>
    <audio id="mediaClip" src="takeMeToChurchHozier.mp3" controls>
        <p>Your browser does not support the audio element</p>
    </audio>
    <br/>
    <input onclick="change();playPause()" type="button" value="Play"       id="button1">
    <br/>
    <input type="range" onchange="setVolume()" id='volume1' min=0 max=1      step=0.01 value='1'>
        </body>
</html>

1 Answer 1

1

In your setVolume() function, change your code to this :

var mediaClip = document.getElementById("mediaClip");
mediaClip.volume = document.getElementById("volume1").value;

Explanation:

I changed the first line of code from var mediaClip = document.getElementById("mediaclip").value; to var mediaClip = document.getElementById("mediaClip"); because to change the attribute or property of an element, you need to use this syntax element.property not element.value.property.

I deleted the second line completely, because neither it meant anything nor it was required there. Think about it, why will you assign the value of an element to the current value of the element???

Your third line (in my code, it is second line) is unchanged.

Sign up to request clarification or add additional context in comments.

1 Comment

Ahhh It works! Thanks so much I've been stuck on this for hours. I know the second line doesn't make a lot of sense hahah I was trying everything I could. Good to know I wasn't as far off as I thought I was.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.