Devlog #4: Music Player
I made a music player! I used some AI since it’s been a while since I coded JavaScript, but I put together the thing myself. Here’s how it works.
First, I get the file from the user in the form of <input id="musicFile" accept"audio/*" type="file">.
Then, I listen for a change in the input by adding an event listener: musicFile.addEventListener("change", loadMusic);.
Once the user adds a file, I fetch the file :const file = this.files[0];.
Then I assign it to a blob URL: musicURL = URL.createObjectURL(file);.
Next, I assign the blob URL to the source tag: musicSource.src = musicURL;.
Finally, I reload the audio tag for the changes to take place: musicPlayer.load();.
Here’s the code:
HTML Code:
<input id="musicFile" type="file" accept="audio/*">
<audio id="musicPlayer" controls>
<source id="musicSource" src="">
</audio>
JavaScript Code:
function loadMusic() {
const file = this.files[0];
if (file) {
if (globalThis.musicURLblob){
URL.revokeObjectURL(globalThis.musicURLblob);
}
globalThis.musicURLblob = URL.createObjectURL(file);
musicSource.src = globalThis.musicURLblob;
musicPlayer.load();
musicPlayer.play();
}
}
let musicURLblob = null;
const musicFile = document.querySelector("#musicFile");
const musicSource = document.querySelector("#musicSource");
const musicPlayer = document.querySelector("#musicPlayer");
musicFile.addEventListener("change", loadMusic);
Comments 0
No comments yet. Be the first!
Sign in to join the conversation.