JavaScript Play Uploaded Audio

后端 未结 3 1523
不知归路
不知归路 2020-11-29 07:11

How do I make it so that when audio is uploaded it can be played? I used this code, but it didn\'t work.



        
3条回答
  •  伪装坚强ぢ
    2020-11-29 07:33

    [EDIT]

    One should not use the FileReader API to load an user selected File into its page.

    Instead one should prefer the URL.createObjectURL(File) method.
    This will return a blobURI, only accessible from user session, which, in case of user File, is just a direct pointer to the original file, thus taking almost nothing in memory.

    input.onchange = function(e){
      var sound = document.getElementById('sound');
      sound.src = URL.createObjectURL(this.files[0]);
      // not really needed in this exact case, but since it is really important in other cases,
      // don't forget to revoke the blobURI when you don't need it
      sound.onend = function(e) {
        URL.revokeObjectURL(this.src);
      }
    }
    
    

    [Previous answer]

    You can't access the full url of a local file with input type="file".

    However you can read the file thanks to the file API

    input.onchange = function(){
      var sound = document.getElementById('sound');
      var reader = new FileReader();
      reader.onload = function(e) {
        sound.src = this.result;
        sound.controls = true;
        sound.play();
        };
      reader.readAsDataURL(this.files[0]);
    }
    
    

提交回复
热议问题