i am a new website learner. So i was making a website based on my father's request and i need to make a button that imports an audio to the tag. There will also be an X button right next to it, but i dont know how to script that, theres also a table for the audio to be in. I've already made the import button, but not the whole thing. Heres a concept of what im actually trying to say:concept
forgot to say, there will also be a keybind button that detects whatever key youre pressing then sets the keybind for it, but thats optional.
Here is my current script.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./style.css">
<title>Index</title>
</head>
<body>
<form action="/action_page.php">
<input type="file" id="real-file" hidden="hidden" accept=".ogg,.wav,.aiff,.mp3,.aac,.flac,.alac,.dsd,.pcm" />
<button type="button" id="custom-button">CHOOSE A FILE</button>
<span id="custom-text">No file chosen, yet.</span>
</form>
<script src="./main.js"></script>
</body>
CSS:
#custom-button {
padding: 10px;
color: white;
background-color: #009578;
border: 1px solid #000;
cursor: pointer;
transition: 0.1s;
}
#custom-button:hover{
background-color: #00b28f;
transition: 0.1s;
}
#custom-text {
margin-left: 10px;
font-family: sans-serif;
color: #aaa;
}
JS:
const realFileBtn = document.getElementById("real-file");
const customBtn = document.getElementById("custom-button");
const customTxt = document.getElementById("custom-text");
customBtn.addEventListener("click", function() {
realFileBtn.click();
});
realFileBtn.addEventListener("change", function() {
if (realFileBtn.value) {
customTxt.innerHTML = realFileBtn.value.match(/[\/\\]([\w\d\s\.\-\(\)] )$/)[1];
} else {
customTxt.innerHTML = "no file chosen, yet.";
}
})
i tried nothing as i dont know how to make it work.
CodePudding user response:
Add an audio tag to your html
<audio id="audio" controls"></audio>
add the following to your js
to get the file use realFileBtn.files[0], then create an url to your file by using window.URL.createObjectURL and set to src of your audio tag to that url
const audio = document.getElementById('audio');
realFileBtn.addEventListener("change", function() {
if (realFileBtn.value) {
customTxt.innerHTML = realFileBtn.value.match(/[\/\\]([\w\d\s\.\-\(\)] )$/)[1];
audio.src = window.URL.createObjectURL(realFileBtn.files[0]);
} else {
customTxt.innerHTML = "no file chosen, yet.";
}
})