如何才能在上传音频时播放?我使用了这段代码,但没有用。
<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,只能从用户 session 访问,在用户文件的情况下,它只是指向原始文件的直接指针,因此几乎不占用内存。
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。
但是,由于 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 播放上传的音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28619550/