Play audio local file with html

笑着哭i 提交于 2019-11-26 11:30:54

问题


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.


回答1:


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>



回答2:


<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




回答3:


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


来源:https://stackoverflow.com/questions/38265242/play-audio-local-file-with-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!