我是一名学生,并且是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>
问题:
有两个按钮,播放和停止。 当我点击播放按钮时,声音正在播放。然后,我点击停止按钮以停止提示音。然后,再次单击播放按钮时,听不到声音!
我做错了什么?
答案 0 :(得分:1)
这是您的解决方案:
$(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>