简体   繁体   English

如何播放对HTML / JavaScript中的输入变量有反应的音频文件?

[英]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. 我试图编写一个HTML / JavaScript文件,根据给定的动物名称播放动物声音(.mp3)。

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! 问题是我不知道如何将mp3文件源用作变量! Can someone help please?? 有人可以帮忙吗?

here are the JavaScript and HTML files which I've written so far: 这是我到目前为止编写的JavaScript和HTML文件:

 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: 给音频标签一个ID并更改其来源:

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

HTML: 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. 但是,您可能想先验证给定的字符串是否是受支持的动物。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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