gpt4 book ai didi

javascript - 网络音频仅播放一次

转载 作者:行者123 更新时间:2023-12-01 01:04:52 25 4
gpt4 key购买 nike

我是一名学生,是 Web API 的初学者。我编写这段代码是为了练习使用 JavaScript 生成简单的音调:

<html>
<body>
Frequency = <input type="number" id="freq"/><br>
Waveform = <input type="text" id="wf"/><br>
<button onclick="start()">Play</button>
<button onclick="stop()">Stop</button>
</body>
<script>
const context=new AudioContext();
const oscillator=context.createOscillator();
oscillator.type='sine';
oscillator.frequency.value=400;
const gain=context.createGain();
oscillator.connect(gain);
gain.connect(context.destination);
function start()
{
oscillator.start();
}
function stop()
{
oscillator.stop();
}
</script>
</html>

问题:

有两个按钮,播放停止。当我点击播放按钮时,就会播放提示音。然后我单击停止按钮来停止提示音。然后,当我再次单击播放按钮时,没有听到任何声音!

我做错了什么?

最佳答案

这是您的解决方案:

 
$(document).ready(function() {
var context = new AudioContext();
var oscillator = context.createOscillator();

oscillator.start();
$("#start").click(function() {
if($('#freq').val()!=""){
oscillator.frequency.value = $("#freq").val();
console.log($("#freq").val());
}else{
oscillator.frequency.value = 400;
}
oscillator.connect(context.destination);
});
$("#stop").click(function() {
oscillator.disconnect(context.destination);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
Frequency = <input type="number" id="freq"/><br>
Waveform = <input type="text" id="wf"/><br>
<button id="start">Play</button>
<button id="stop">Stop</button>
</body>

</html>

关于javascript - 网络音频仅播放一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55742307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com