简体   繁体   中英

How to play an audio file that reacts to an input variable in HTML/JavaScript?

I trying to write an HTML/JavaScript file which would play an animal sound (.mp3) according to the given name of an animal.

The script prompts the user to enter an animal's name. After the user entered the name, the animal's name is appeared in the output box. The code searches in my audio directory for the given animal's name and when the name is found, then (and only then) the audio tag of the sound is loaded. The user can press the play key to hear it (if he chooses so). This is illustrated in the given picture: 在此处输入图片说明

The problem is that I don't know how to use the mp3 file source as a variable! Can someone help please??

here are the JavaScript and HTML files which I've written so far:

 function animalVoice(){ // Get the Animal name from the text field theAnimal=document.animals.newAnimal.value; document.animals.outAnimal.value=theAnimal; //writing the input again in the "output" field" } 
 <!DOCTYPE html> <html <head> <script type="text/javascript" src="audio_check.js"></script> </head> <body> <p>please enter the animal's name here: </p> <form name="animals"> <input type="text" name="newAnimal" size ="30" /> <input type="button" name="animal" value="find the sound" onclick="animalVoice();"> <br/> <h4>output:</h4> <textarea cols = "30" rows = "2" name="outAnimal"> </textarea> <audio src="audio/cow.mp3" <!--how to implement the input variable theAnimal???--> prelaod = "auto" controls </audio> </form> </body> </html> 

Give the audio tag an ID and change its source:

function animalVoice(){
    // Get the Animal name from the text field
    theAnimal=document.animals.newAnimal.value; 
    document.getElementById("myPlayer").src = "audio/" + theAnimal + ".mp3"; 
}

HTML:

<audio
    src="audio/cow.mp3"
    id="myPlayer"
    preload="auto"
    controls>     
</audio> 

However you probably want to first validate that the given string is a supported animal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM