如何加载用户上传的HTML声音



我目前正在使用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,并返回一个Blob URI。

这是您的代码:

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()">

最新更新