You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中点击按钮后插入变量并显示audio元素

解决方案:动态生成并加载Bing文本转语音音频

我来帮你实现这个功能!我们需要修改现有代码,让点击「GET AUDIO」按钮后,能动态获取输入的文本和选择的语言,生成正确的音频链接,然后更新并显示audio播放器。以下是完整的实现代码和详细说明:


完整代码

<select id="langSelect">
 <option value="en">English</option>
 <option value="vi">Vietnamese</option>
</select>
<br>
<textarea id="langSource" placeholder="Enter text or webpage URL here" maxlength="5001" aria-label="Text to be translated" style="background: transparent none repeat scroll 0% 0% !important; z-index: auto; position: relative; line-height: 48px; font-size: 40px; transition: none 0s ease 0s;"></textarea>
<br>
<button onclick="getContentTranslate()">GET AUDIO</button>
<br>
<!-- 给audio和source添加id,默认隐藏播放器 -->
<audio id="audioPlayer" controls autoplay style="display:none;">
 <source id="audioSource" src="" type="audio/mpeg">
</audio>

<script>
function getContentTranslate() {
 // 获取输入的文本和选中的语言值
 var contentSource = document.getElementById('langSource').value.trim();
 var selectedValue = document.getElementById("langSelect").value;

 // 先校验输入是否为空,避免无效请求
 if (!contentSource) {
   alert("请输入要转换为音频的文本哦!");
   return;
 }

 // 对文本进行URL编码,处理空格、特殊字符等
 var encodedText = encodeURIComponent(contentSource);

 // 动态构建符合要求的音频URL
 var audioUrl = `https://www.bing.com/tspeak?&format=audio%2Fmp3&language=${selectedValue}&IID=translator.5034.2&text=${encodedText}`;

 // 获取音频播放器和源元素
 var audioPlayer = document.getElementById('audioPlayer');
 var audioSource = document.getElementById('audioSource');

 // 更新音频源地址
 audioSource.src = audioUrl;

 // 加载新的音频资源并显示播放器
 audioPlayer.load();
 audioPlayer.style.display = "block";
}
</script>

关键步骤说明

  • 添加元素标识:给audio和source标签加上id,方便在JS中快速获取元素;默认设置audio为display:none,只有获取到音频后才显示。
  • 输入校验:先检查用户是否输入了文本,避免发送空请求,同时给用户友好提示。
  • URL编码处理:使用encodeURIComponent()对文本内容进行编码,确保空格、标点等特殊字符能正确传递到Bing的语音API,避免请求失败。
  • 动态构建音频链接:用ES6模板字符串拼接URL,将选中的语言和编码后的文本替换到对应参数位置。
  • 更新并加载音频:修改source的src属性后,调用audioPlayer.load()让浏览器重新加载新的音频资源,最后设置播放器为显示状态。

这样修改后,点击按钮就能根据用户输入动态生成音频并播放啦!

内容的提问来源于stack exchange,提问作者Ave

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:30:24