I have an HTML audio tag and an HTML file input tag, as shown below. I'd like users to use the Upload File button to select a song from their computer, then play it using the audio tag.
<audio id="audio">
<source src="" id="thesource" />
</audio>
<input type="file" id="upload" title="Upload File" />
How do I let users upload audio files from their computer and play it? This must be done locally, as it is being used in a downloadable web app I am creating.
EDIT: Long ago, after lots of hard work and rediscovering past projects, I developed a solution to this question by converting some image-uploading code from one of my past projects into audio-uploading code. Now, years after I originally asked this question, I feel stupid for not realizing that answer earlier. I posted and edited the answer down below for any people who also need this.
I originally said there was no answer -- I was wrong. I have found the answer.
function handleFiles(event) {
var files = event.target.files;
$("#src").attr("src", URL.createObjectURL(files[0]));
document.getElementById("audio").load();
}
document.getElementById("upload").addEventListener("change", handleFiles, false);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="upload" />
<audio id="audio" controls>
<source src="" id="src" />
</audio>
This does exactly what I wanted -- it allows uploading of any audio file and plays it. Try uploading any music from your computer into the snippet.
Note: Browsers like Google Chrome constantly update how and when audio/video can be played for evolving convenience or security. This answer is currently working, but if it is no longer working at any point in the future, please post a comment below so I can fix any problems that emerge.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With