9

I'm trying to do something like this.

But I don't know why I'm not getting this thing work. Here it is the codepen example:

$('input').on('change', function(e) {

  var file = e.currentTarget.files[0];

  var reader = new FileReader();

  reader.onload = function(e) {
    $('audio source').attr('src', e.target.result);
  }   

  reader.readAsDataURL(file);
});

The source tag is receiving the base64 mp3 file, but it doesn't load the file into browser.

Tomás Francisco
  • 791
  • 3
  • 7
  • 15

3 Answers3

18

You set the src attr directly on the audio element. fiddle

var $audio = $('#myAudio');
$('input').on('change', function(e) {
  var target = e.currentTarget;
  var file = target.files[0];
  var reader = new FileReader();
  
  console.log($audio[0]);
   if (target.files && file) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $audio.attr('src', e.target.result);
            $audio.play();
        }
        reader.readAsDataURL(file);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file">
<audio controls id="myAudio" autoplay></audio>
oshell
  • 8,923
  • 1
  • 29
  • 47
  • 1
    That works!! How is it possible? Every source that I've checked describe that the src file should be on source tag inside audio tag, not in audio. Thank you so much! – Tomás Francisco Jul 08 '16 at 12:50
  • Is there a way to make the input allow multiple files and so create a playlist instead of one file at a time? – Lamar May 24 '17 at 19:42
0
<audio controls>
<source src="yoraudio.ogg" type="audio/ogg">
<source src="youraudio.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>

For more help visit

This is the simplest way to play audio

Mr. Panda
  • 17
  • 2
0

In UWP you can play a file directly that you can get by name from the Music Library as shown below. Just get permission to access the Music Library by checking the library in the "Capabilities" tag of your project properties.

picksinglefile();
        var l = Windows.Storage.KnownFolders.musicLibrary;
        var f = localStorage.getItem("alarmname").toString();
        l.getFileAsync(f).then(function (file) {
            // storagefile file is available
            var s = window.URL.createObjectURL(file);  // its a storage file, so create URL
            player1.setAttribute("src", s);
            player1.play(); // if autoplay is false or off
        });


function picksinglefile() {
// Create the picker object and set options
var fop = new Windows.Storage.Pickers.FileOpenPicker();
fop.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.musicLibrary;
fop.fileTypeFilter.replaceAll([".mp3", ".wav"]);
fop.pickSingleFileAsync().then(function (file) {
    if (file) {
        localStorage.setItem("alarmname", file.name.toString());
    } else {
        alert("Operation Cancelled");
    }
});
pollaris
  • 1,281
  • 17
  • 20