JavaScript 播放上传的音频 [英] JavaScript Play Uploaded Audio

查看:23
本文介绍了JavaScript 播放上传的音频的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何制作,以便在上传音频时可以播放?我用过这段代码,但没有用.

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>

推荐答案

不应使用 FileReader API 将用户选择的文件加载到其页面中.

相反,人们应该更喜欢 URL.createObjectURL(File) 方法.
这将返回一个 blobURI,只能从用户会话访问,在用户 File 的情况下,它只是指向原始文件的直接指针,因此几乎不占用内存.

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>

您无法使用 input type="file" 访问本地文件的完整 url.

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

但是您可以阅读该文件,这要归功于 文件 API

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

<input type="file" id="input"/>
<audio id="sound"></audio>

这篇关于JavaScript 播放上传的音频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆