gpt4 book ai didi

javascript - 一键切换 - JavaScript - Web Audio API

转载 作者:行者123 更新时间:2023-11-30 06:34:30 25 4
gpt4 key购买 nike

我是一名音频工程师,刚刚开始使用 JavaScript 和 HTML5,特别是 WEB 音频 API。

我有这个连接到目标(输出)的振荡器代码。这是代码

我想要一个按钮来连接和断开振荡器到目的地我成功启动了它,但无法断开连接。

<html>
<head>
<script>
//creating the context
context = new webkitAudioContext(); //allways the first code for audio API
function osc1(frequency){ // Creating a function that has an oscillator going to gainNode and then going to the destination

//creating AudioNodes and AudioParams

//creating OscillatorNode
var oscillator = context.createOscillator(); //creating Node's as Variables
oscillator.type = 0; //0 is a sine wave
oscillator.noteOn(0); // turning on the oscillator
oscillator.frequency.value = frequency;// telling that frequency in () of the function equals to what


//creating GainNode
var gain = context.createGainNode(); // creating the Gain node
gain.gain.value = 1; // setting up the value for gain node


//Making the connections
oscillator.connect(gain); // connecting oscillator to gain
gain.connect(context.destination); // connecting gain to destination (speakers)
}; // now we have a function called osc1(we can put frequency in here) then we can re call


</script>
</head>

<body>
<input type="button" value="on" onClick="osc1(500);" />

</body>

</html>

我知道断开连接的代码是oscillator.disconnect();,但我不知道如何执行它。

最佳答案

也许您想在函数外声明振荡器变量:

var context = new webkitAudioContext();
var oscillator = context.createOscillator();
function osc1(frequency){
var button = document.getElementsByTagName('input')[0];
if (button.value === 'off') {
button.value = 'on';
oscillator.disconnect();
} else {
button.value = 'off';
// same as your original code (connect, noteOn...)

关于javascript - 一键切换 - JavaScript - Web Audio API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15462167/

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