10

Is it possible to use an audio file from the user's hard drive as the src attribute for an HTML5 <audio> tag? Maybe through an <input type="file" />? This might not be particularly useful in production, but I'm still curious if it can be done.

Rob Allsopp
  • 3,309
  • 5
  • 34
  • 53
  • You should be able to use the same techniques discussed [Play Local (hard-drive) video.][1] [1]: https://stackoverflow.com/questions/8885701/play-local-hard-drive-video-file-with-html5-video-tag – Andrew Lewis Feb 12 '14 at 19:09

2 Answers2

20

I can think of two ways.

Within your audio tag:

src="file:///C:/.../file.mp3"

or you could use a Blob using the file API.

HTML:

<input type="file"></input>

JS:

audio.src = URL.createObjectURL(document.getElementsByTagName('input')[0].files[0]);
Oreo
  • 529
  • 3
  • 16
Paul Martin
  • 391
  • 2
  • 4
  • nice, the file API method worked like a charm for me! – Rob Allsopp Feb 12 '14 at 19:34
  • also of note. If you want to change the audio tag every time the file changes, there is an 'change' event for the input tag. that will fire every time you change the file in the input tag. – Paul Martin Feb 12 '14 at 19:39
  • 3
    I just get `Not allowed to load local resource`. Stupid damn security. Surely feeding an `.mp3` directly into the `src` of an `audio` element should be supported? – Alex McMillan Jul 23 '15 at 09:38
  • @AlexMcMillan It should not. Or else, a random script your browser loads, could play through your music collection at once. – Marcel May 16 '21 at 20:41
0

This worked for me on localhost, the mp3 imported via require("...") has a property 'default' which contains the relevant src

const MissingAudio = require("../media/missingAudio.mp3");
<audio src={MissingAudio.default}></audio>
Peter
  • 1