Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k 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 Reply

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...