Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何加载用户上传的HTML声音?_Javascript_Html_Input - Fatal编程技术网

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

Javascript 如何加载用户上传的HTML声音?,javascript,html,input,Javascript,Html,Input,我目前正在使用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");

我目前正在使用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()">
但这不起作用,因为我很确定声音构造函数需要一个文件路径


是否有人知道任何变通方法/解决方案?

声音功能中,而不是:

this.sound.src = src;
Put:

this.sound.src = URL.createObjectURL(src);
URL.createObjectURL(src)
将创建一个对象URL,并返回一个BlobURI

这是您的代码:

功能声音(src){
this.sound=document.createElement(“音频”);
this.sound.src=URL.createObjectURL(src);
this.sound.setAttribute(“预加载”、“自动”);
this.sound.setAttribute(“控制”、“无”);
this.sound.style.display=“无”;
document.body.appendChild(this.sound);
this.play=函数(){
这个。声音。播放();
}
this.stop=函数(){
这个.sound.pause();
}    
this.sound.onend=函数(e){
revokeObjectURL(this.src);
}
}
函数onUpload(){
设fname=document.getElementById('mp3File').files[0];
mySound=新声音(fname);
mySound.play();
}
this.sound.src = URL.createObjectURL(src);