JavaScript播放上传的音频 [英] JavaScript Play Uploaded Audio
本文介绍了JavaScript播放上传的音频的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何制作音频上传时可以播放?
< input type =fileid =audioonchange =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的情况下,它只是一个直接指向原始文件,因此在内存中几乎没有任何东西。
$ b
input.onchange = function( e){var sound = document.getElementById('sound'); sound.src = URL.createObjectURL(this.files [0]); //在这种情况下并不是真正需要的,但是由于在其他情况下非常重要,//不要忘记在不需要的时候撤销blobURI sound.onend = function(e){URL.revokeObjectURL( this.src); }}
< input type =fileid = input/>< audio id =soundcontrols>< / audio>
$ b
你不能使用 input type =来访问本地文件的完整url文件
。
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 =fileid =input/>< audio id =sound>< / 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>
解决方案
[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>
[Previous answer]
You can't access the full url of a local file with input type="file"
.
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屋!
查看全文