Search code examples
javascripthtmlaudioscript-tag

Using JavaScript to control mp3 playback in HTML


I am trying to control an mp3 through click events.

<!DOCTYPE html>
<html>
<body>

<audio id="demo" autoplay="true" hidden="hidden">
   <source src="Lute.mp3" type="audio/mpeg">
   Your browser does not support the audio element.
</audio>

<div onmousedown="WhichButton(event)">
  <img src="Birch-Forest.jpg" alt="A birch forest in the fall"
  style="width:600px;height:572px">
</div>

<script>
var playing = false;
function WhichButton(event) {
    if (event.button == 0) {
    document.getElementById('demo').volume-=0.1;
    }
    else if (event.button == 1 && playing) {
    document.getElementById('demo').pause;
    } 
    else if (event.button == 1 && !playing) {
    document.getElementById('demo').play;
    } 
    else if (event.button == 2) {
    document.getElementById('demo').volume+=0.1;
    } 
}
</script>

</body>
</html>

This code loads the image and starts audio playback, but the controls do not work. I don't really know what I'm doing, just a beginner in HTML and JavaScript.


Solution

  • You have some errors in your script... let's see:

    1. You initialize the playing variable as false, but your audioplayer has autoplay set on true... so maybe, just for clarity, your variable should be initialize to true or renamed to pausing. However this is not an error :)
    2. The pause and play are functions of your audioplayer so if you wanna invoke them you have to use the parenthesis, like this: document.getElementById('demo').pause();. Vice versa volumeis a property so you don't need the parenthesis.
    3. Now, you want to play the audio when it is paused and pause it when it is playing. Correctly you have a boolean variable for this (playing), but you never change its value!

    Your code with some corrections:

    <script>
    var playing = true; // Point 1
    var audioPlayer = document.getElementById('demo');
    function WhichButton(event) {       
        if (event.button == 0 && audioPlayer.volume > 0) {
            audioPlayer.volume-=0.1;
        }
        else if (event.button == 1 && playing) {
            audioPlayer.pause(); // Point 2
            playing = false; // Point 3
        } 
        else if (event.button == 1 && !playing) {
            audioPlayer.play();
            playing = true;
        } 
        else if (event.button == 2 && audioPlayer.volume < 1) {
            audioPlayer.volume+=0.1;
        }   
    }
    </script>