Search code examples
javascripthtmlaudioselected

How do I use Javascript to Select Audio File from Button Value


So I have an array of buttons all with different values and I want them play the song with it's number value, when clicked. All of the files are numbered, i.e. 1.mp3, 2.mp3, 3.mp3, etc.

Is there a way of doing it without a lot of repeating Javascript code for each song.

Here is my HTML:

<audio id="player">
        <source id="sourceMp3" src="" type="audio/mp3">
        Your browser does not support the audio element.
</audio>

<button onclick="loadSong()" value="1">1</button>
<button onclick="loadSong()" value="2">2</button>
<button onclick="loadSong()" value="3">3</button>
<button onclick="loadSong()" value="4">4</button>
<button onclick="loadSong()" value="5">5</button>

Here is my JavaScript:

function loadSong(){

var player=document.getElementById('player');
var songNo = document.getElementByTagName('button').value;
var sourceMp3=document.getElementById('player');

sourceMp3.src='songs/' + songNo + '.mp3;

player.load();
player.play(); 

}

Any suggestions would be greatly appreciated.


Solution

  • Your call in the JS portion should be:

    var sourceMp3=document.getElementById('sourceMp3');
    

    Then

    sourceMp3.src='songs/' + songNo + 'mp3';
    

    should work.

    Notice, you should pick the 'src' of the <source>-tag, not the <audio>-tag

    also, I would add a function-call with the buttons: - and then define your function like this: function loadSong(songNo)...

    So, your code could look like this:

    <audio id="player">
        <source id="sourceMp3" src="" type="audio/mp3">
        Your browser does not support the audio element.
    </audio>
    
    <button onclick="loadSong(1)">1</button>
    <button onclick="loadSong(2)">2</button>
    <button onclick="loadSong(3)">3</button>
    <button onclick="loadSong(4)">4</button>
    <button onclick="loadSong(5)">5</button>
    

    And the JS:

    function loadSong(songNo) {
    var player=document.getElementById('player');
    var sourceMp3=document.getElementById('sourceMp3');
    sourceMp3.src='songs/' + songNo + '.mp3';
    
    player.load();
    player.play();