Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
963 views
in Technique[技术] by (71.8m points)

file upload - JavaScript Play Uploaded Audio

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

<input type="file" id="audio" onchange="playFile(this)" />
<audio id="sound"></audio>
<script type="text/javascript">
    function playFile(obj){
        var url=document.getElementById("audio").url;
        document.getElementById("sound").src=url;
        document.getElementById("sound").play()
    }
</script>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

[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);
  }
}
<input type="file" id="input"/>
<audio id="sound" controls></audio>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...