![](/img/trans.png)
[英]How do play an audio file on a button click using HTML and JavaScript?
[英]How to play an audio file that reacts to an input variable in HTML/JavaScript?
我试图编写一个HTML / JavaScript文件,根据给定的动物名称播放动物声音(.mp3)。
该脚本提示用户输入动物的名字。 用户输入名称后,动物名称将出现在输出框中。 该代码在我的音频目录中搜索给定动物的名字,当找到名字时,然后(并且只有这样)才加载声音的音频标签。 用户可以按播放键收听(如果他选择的话)。 在给定的图片中对此进行了说明:
问题是我不知道如何将mp3文件源用作变量! 有人可以帮忙吗?
这是我到目前为止编写的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>
给音频标签一个ID并更改其来源:
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>
但是,您可能想先验证给定的字符串是否是受支持的动物。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.