electrikmilk
electrikmilk

Reputation: 1043

Change <audio> tag src by function

I'm making an audio player script that changes the src="" of the <audio> tag, I don't like doing because I'm not doing tracks.

The user clicks on this link:

<a href="#play" onclick="playAudio('song.mp3');">Play</a>

Then this receives the function:

   function playAudio(file)
    {
    var audio = file;
    }
    if(audio !== '') {
    document.getElementById('player').src = 'music/'+audio;
    }
    else {

    }

For this player:

<audio id="player" src="" controls></audio>

I've tried changing different things about the script but it's no good.

Why won't it change the audio?

Upvotes: 1

Views: 3443

Answers (1)

Michał Szałapski
Michał Szałapski

Reputation: 331

Your function ends at the start, because you have the closing brace } in the wrong place:

function playAudio(file)
    {
    var audio = file;
    }

This should be written as:

 function playAudio(file)
    {
    var audio = file;
    if(audio !== '') {
    document.getElementById('player').src = 'music/'+audio;
    }
    else {

    }
}

Also, id isnt a href, this should be:

<a href="#play" id="play" onclick="playAudio('song.mp3');">Play</a>

Upvotes: 3

Related Questions