我一直在尝试第一次学习文件api。我想播放一首歌。但是没有声音产生。我试图使用readAsArrayBuffer()方法,因为我发现它用于解码音频文件。但不幸的是没有发生任何事情。这可以解决。谢谢:)
<html>
<head>
<style>
#files{
display:none;
}
#lab{
display:inline-block;
width:70px;
height:30px;
background:lime;
padding:5px;
}
#lab:hover{
cursor:pointer;
}
p{border:1px solid black;}
</style>
</head>
<body>
<form>
<input type='file' id='files'>
<label for='files' id='lab' style='text-decoration:underline;color:red;'>click</label>
</form>
<p>fileName :<span id='name'></span></p>
<script>
var music;
function init(){
document.getElementById('files').addEventListener('change',myfile,false);
}
function myfile(evt){
var files=evt.target.files[0];
if(files.type !='audio/mpeg'){
alert('no audio file');
return;
}
var reader=new FileReader();
reader.onload=function(e){
music=e.target.result;
var audio=new Audio();
audio.src=music;
audio.play();
}
reader.readAsArrayBuffer(files);
}
window.addEventListener('load',init,false);
</script>
</body>
</html>
答案 0 :(得分:1)
尝试
var music;
function init() {
document.getElementById('files')
.addEventListener('change',myfile,false);
};
function myfile(evt) {
evt.preventDefault();
evt.stopPropagation();
var files=evt.target.files[0];
// test for additional file types
var types = !((/audio\/mpeg|audio\/mp3|audio\/mp4|audio\/ogg|audio\/x+|wav/).test(files.type));
if(!!types){
alert('no audio file');
return;
};
var reader=new FileReader();
reader.onload=function(e){
music=e.target.result;
// see link
var audio = new Audio(music);
audio.play();
};
// substitute `readAsDataURL` for `readAsArrayBuffer`
reader.readAsDataURL(files);
};
window.addEventListener('load',init,false);
jsfiddle http://jsfiddle.net/guest271314/1314q3q9/
见
https://developer.mozilla.org/en-US/docs/Web/API/HTMLAudioElement#Description