Albert
Albert

Reputation: 11

(JS/HTML) How do I pull an MP3 from the local directory and assign it to an audio element?

I am part of a team building a basic audio visualizer and I am in charge of the functions. I have an input button coded as "input id="audioFile" type="file" accept="audio/*" which opens the computer's directory and allows you to select a file. My question is how can I assign the selected file to an audio element such that I can manipulate it with other functions?

Upvotes: 1

Views: 314

Answers (1)

TechnicalChaos
TechnicalChaos

Reputation: 452

Untested stuff here, but a brief overview. You need to do this in a couple of steps. Add a callback to your file:

document.getElementById('audioFile').addEventListener('change', changeMusic, false);

And then make a function with that name changeMusic that gets the file name:

function changeMusic(evt) {
    var file = evt.target.files;
    file = file[0]; 
    // get the first element in list of filenames 

    var filename = URL.createObjectURL(file);
    // createObjectUrl gets the files location and makes it a path.

    document.getElementById('the_audio_player').src = filename;
    // change source of audio
}

edit: couple of typos.

Upvotes: 1

Related Questions