1

I'm trying to load local audio file by the (input:file) Elem and when I passe it to the audio constructor Audio() as an object it doesn't load/play.

file Object params&meths:

lastModified: 1586969070000
lastModifiedDate: Wed Apr 15 2020 18:44:30 GMT+0200 (Central European Summer Time) {}
name: "audio.mp3"
size: 15235482
type: "audio/mpeg"
webkitRelativePath: ""

i tried giving just the name, relative path but nothing seems to work.

Js Code

var track = new Audio(file Object);
track.play();

when I tried to troubleshoot:

console.log(track);

<audio preload="auto" src="[object File]">
#shadow-root (user-agent)
</audio>

and when play() triggered:

GET http:// **Local IP** /[object%20File] 404 (Not Found)
index.html:1 Uncaught (in promise) DOMException: Failed to load because no supported source was found.

although before I started the project I did a little test and it worked perfectly but now it doesn't... any help will be amazing thanks

2
  • var track = new Audio(file Object); - wrong way. You must insert URL into new Audio constructor, not file Object Commented Aug 6, 2020 at 20:42
  • @DimaVak that's the point. I'm here loading a file with (input:file) so I don't have access to the real file URL although there is a relative one but it appears as an empty string ""... Commented Aug 6, 2020 at 20:55

1 Answer 1

1

That works in another way. You must add your file, after that catch his node(input), and from that create a URL. This URL work like a normal URL, but with your local files.

Sorry for that bad explanation, here you can read more

https://javascript.info/file https://javascript.info/blob

Too I create a snippet. Chose local file -> Add SRC to "player' -> Click Play btn.

const btn = document.querySelector("#btn");
const yourMusic = document.querySelector("#yourMusic");
btn.addEventListener("click", () => {
  let music = document.querySelector("#file").files[0];
  yourMusic.src = URL.createObjectURL(music);
});
<input id="file" type="file" />
    <button id="btn">Add to player</button>
    <audio controls id="yourMusic"></audio>

Sign up to request clarification or add additional context in comments.

1 Comment

Is it answer for your question?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.