我在 html5 中实现音频播放器,它具有用于加载和播放 mp3 文件的拖放选项,但我在播放文件时遇到问题。
当文件被拖放到该区域时,我可以在对象的控制台属性中看到,但由于 Web 浏览器的安全性,没有关于绝对路径的信息。
有没有选择,如何以这种方式播放 mp3 ?
index.html 和正文内容:
<div style="border: 1px solid black; width: 200px; height: 50px; padding: 10px;"" id="cudl">add file here</div>
<div id="play" style="border: 1px solid black; width: 200px; height: 50px; padding: 10px;">PLAY</div>
<div id="pause" style="border: 1px solid black; width: 200px; height: 50px; padding: 10px;">PAUSE</div>
<div id="progress" style="width: 1000px; height: 50px; background: black; "><div id="time" style="width: 0%; height: 50px; background: green;"></div></div>
javascript:
window.onload = function () {
var cudl = document.getElementById("cudl");
cudl.addEventListener("dragover", function (ev) {
ev.preventDefault();
}, false);
cudl.addEventListener("drop", function (ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("audio/mpeg");
var allAudio = document.getElementsByTagName("audio");
if (allAudio.length > 0) {
for (var i = 0; i < allAudio.length; i++) document.body.removeChild(allAudio[i]);
}
var audio = document.createElement("audio");
audio.setAttribute("src", ev.dataTransfer.files[0].name);
document.body.appendChild(audio);
console.log("append file");
console.log(ev.dataTransfer.files[0]);
audio.addEventListener("durationchange", function () {
console.log("dc " + this.duration);
});
audio.addEventListener("timeupdate", function () {
//console.log("ct " + this.currentTime);
var prog = document.getElementById("time");
prog.style.width = Math.floor(this.currentTime / this.duration * 100) + "%";
});
var play = document.getElementById("play");
play.addEventListener("click", function () {
document.getElementsByTagName("audio")[0].play();
});
var pause = document.getElementById("pause");
pause.addEventListener("click", function () {
document.getElementsByTagName("audio")[0].pause();
});
}, false);
};