Home > Software design >  playing audio in JavaScript from URL with variable
playing audio in JavaScript from URL with variable

Time:12-07

What I'm trying to make is a input that when you type the song name it plays. First what I tried was

function myFunction() {
  var id = document.getElementById("myInput").value;
var audio = 'https://bobzilla07.github.io/Music_Tap/'   id 
  var audio = new Audio ('audio');
 audio.play();

with the html code of

<input id="myInput" type="text">
<button onclick="myFunction()">play</button>

Which didn't work

so I though what if I made it so

function myFunction() {
var id = document.getElementById("myInput").value;
var audio = new Audio 'https://bobzilla07.github.io/Music_Tap/'   id;
audio.play();

to which is still didn't work. Does anybody have any idea on how to fix it so it works?

Edit: Im not good with json or even know what im doing btu would there be a possibilty to get the input from <input id="myInput" type="text"> <button onclick="myFunction()">play</button>

and put it in json to then call the audio from the link https://bobzilla07.github.io/Music_Tap/${song}.mp3 with ${song} being the input from the html input

CodePudding user response:

I believe you have to pass the extension here as well. This does work because this server is CORS enabled.

form.addEventListener("submit", myFunction)
function myFunction(e) {
  e.preventDefault();
  audio.src = 'https://bobzilla07.github.io/Music_Tap/'   myInput.value   '.mp3';
  audio.play();
}
audio { display:none;}
<form id="form">
  <input id="myInput" value="Panic-Song">
  <input type="submit">
</form>
<audio controls id="audio"></audio>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Song list

CodePudding user response:

You can do it like this:

let id = document.getElementById("myInput").value;
let audio = new Audio(`https://bobzilla07.github.io/Music_Tap/${id}.mp3`);
audio.play();

Now you can search for the file names of your songs. Like 1979 will play 1979.mp3.

  • Related