decode & play a song using html5 file api

僤鯓⒐⒋嵵緔 提交于 2019-12-25 03:26:25

问题


i have been trying to learn the file api for the first time.Here i want to play a song .But no sound is generating .I tried to use readAsArrayBuffer() method as i found it is used to decode audio files.But unfortunately nothing happened.how this can it be solved.thanks :)

<html>

<head>
<style>
   #files{
     display:none;
   }
   #lab{
     display:inline-block;
     width:70px;
     height:30px;
     background:lime;
     padding:5px;
   }
   #lab:hover{
     cursor:pointer;
   }
   p{border:1px solid black;}
</style>
</head>
<body>
  <form>
    <input type='file' id='files'>
    <label for='files' id='lab' style='text-decoration:underline;color:red;'>click</label>
  </form>
  <p>fileName :<span id='name'></span></p>



   <script>
     var music;
     function init(){


      document.getElementById('files').addEventListener('change',myfile,false);

     }
    function myfile(evt){
      var files=evt.target.files[0];

      if(files.type !='audio/mpeg'){
           alert('no audio file');
           return;
      }
      var reader=new FileReader();
      reader.onload=function(e){
               music=e.target.result;

               var audio=new Audio();
               audio.src=music;
               audio.play();


      }
      reader.readAsArrayBuffer(files);

    }


window.addEventListener('load',init,false);
</script>
</body>
</html>

回答1:


Try

     var music;
     function init() {
      document.getElementById('files')
      .addEventListener('change',myfile,false);
     };
    function myfile(evt) {
      evt.preventDefault();
      evt.stopPropagation();
      var files=evt.target.files[0];
         // test for additional file types
        var types = !((/audio\/mpeg|audio\/mp3|audio\/mp4|audio\/ogg|audio\/x+|wav/).test(files.type));

      if(!!types){
           alert('no audio file');
           return;
      };

      var reader=new FileReader();
      reader.onload=function(e){
               music=e.target.result;
               // see link
               var audio = new Audio(music);              
               audio.play();
      };
      // substitute `readAsDataURL` for `readAsArrayBuffer`
      reader.readAsDataURL(files);
    };
window.addEventListener('load',init,false);

jsfiddle http://jsfiddle.net/guest271314/1314q3q9/

See

https://developer.mozilla.org/en-US/docs/Web/API/HTMLAudioElement#Description



来源:https://stackoverflow.com/questions/25232966/decode-play-a-song-using-html5-file-api

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