如何使音频上传后可以播放?我使用了这段代码,但它不起作用。
<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>
[EDIT]
不应使用 FileReader API 将用户选择的文件加载到其页面中。
相反,人们应该更喜欢URL.createObjectURL(File)
method.
这将返回一个 blobURI,只能从用户会话访问,对于用户文件来说,它只是指向原始文件的直接指针,因此几乎不占用内存。
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>
[之前的回答]
您无法使用以下命令访问本地文件的完整 urlinput type="file"
.
不过,您可以通过以下方式阅读该文件file API https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications
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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)