我目前正在使用HTML的音频标签来播放本地目录中的MP3文件,并使用W3Schools关于游戏声音的教程中的以下代码:
function sound(src) {
this.sound = document.createElement("audio");
this.sound.src = src;
this.sound.setAttribute("preload", "auto");
this.sound.setAttribute("controls", "none");
this.sound.style.display = "none";
document.body.appendChild(this.sound);
this.play = function(){
this.sound.play();
}
this.stop = function(){
this.sound.pause();
}
}
这使我可以使用简单的代码:
function loadSound(){
mySound = new sound("resources/songs/twinkle.mp3");
}
从这里,我可以使用mySound.play()
,一切正常。
但是现在,我希望任何使用我的网站的人都可以上传自己的MP3文件。
我正在使用HTML的输入标签,以允许用户上传其文件:
<input type="file" class="custom-file-input" id="mp3File" onchange="onUpload()">
然后尝试此:
function onUpload(e){
song = document.getElementById("mp3File").files[0];
mySound = new sound(song);
mySound.play()
}
但是那行不通,因为我很确定声音构造函数期望文件路径。
有人知道任何解决方法/解决方案吗?
sound
功能中,而不是:this.sound.src = src;
放置:
this.sound.src = URL.createObjectURL(src);
[URL.createObjectURL(src);
将创建一个对象URL,并将返回一个BlobURI。这是您的代码:
function sound(src) { this.sound = document.createElement("audio"); this.sound.src = URL.createObjectURL(src); this.sound.setAttribute("preload", "auto"); this.sound.setAttribute("controls", "none"); this.sound.style.display = "none"; document.body.appendChild(this.sound); this.play = function(){ this.sound.play(); } this.stop = function(){ this.sound.pause(); } this.sound.onend = function(e) { URL.revokeObjectURL(this.src); } } function onUpload(){ let fname = document.getElementById('mp3File').files[0]; mySound = new sound(fname); mySound.play(); }
<input type="file" class="custom-file-input" id="mp3File" onchange="onUpload()">