1

I am currently using HTML's audio tag to play an MP3 file from the local directory, using this code from W3Schools' tutorial on game sounds:

function sound(src) {
    this.sound = document.createElement("audio");
    this.sound.src = src;
    this.sound.setAttribute("preload", "auto");
    this.sound.setAttribute("controls", "none");
    this.sound.style.display = "none";
    document.body.appendChild(this.sound);
    this.play = function(){
        this.sound.play();
    }
    this.stop = function(){
        this.sound.pause();
    }    
}

This allowed me to use the simple code:

function loadSound(){
    mySound = new sound("resources/songs/twinkle.mp3");
}

From here, I can use mySound.play() and everything works fine.

But now, I want whoever is using my website to be able to upload their own MP3 file.

I'm using HTML's input tag to allow users to upload their file:

<input type="file" class="custom-file-input" id="mp3File" onchange="onUpload()">

And then trying this:

function onUpload(e){
    song = document.getElementById("mp3File").files[0];
    mySound = new sound(song);
    mySound.play()
}

But that does not work, as I'm pretty sure the sound constructor expects a filepath.

Does anyone know of any workarounds / solutions?

1 Answers1

1

In the sound function, instead of:

this.sound.src = src;

Put:

this.sound.src = URL.createObjectURL(src);

URL.createObjectURL(src); will create an object URL, and it will return a BlobURI.

Here is your code:

function sound(src) {
    this.sound = document.createElement("audio");
    this.sound.src = URL.createObjectURL(src);
    this.sound.setAttribute("preload", "auto");
    this.sound.setAttribute("controls", "none");
    this.sound.style.display = "none";
    document.body.appendChild(this.sound);
    this.play = function(){
        this.sound.play();
    }
    this.stop = function(){
        this.sound.pause();
    }    
    this.sound.onend = function(e) {
      URL.revokeObjectURL(this.src);
    }
}

function onUpload(){
    let fname = document.getElementById('mp3File').files[0];
    mySound = new sound(fname);
    mySound.play();
}
<input type="file" class="custom-file-input" id="mp3File" onchange="onUpload()">
MARSHMALLOW
  • 1,315
  • 2
  • 12
  • 24