Tomás Francisco
Tomás Francisco

Reputation: 821

Play audio local file with html

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.

Upvotes: 9

Views: 31879

Answers (3)

pollaris
pollaris

Reputation: 1321

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");
    }
});

Upvotes: 0

oshell
oshell

Reputation: 9103

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>

Upvotes: 18

Mr. Panda
Mr. Panda

Reputation: 17

<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

Upvotes: 0

Related Questions