编程语言
首页 > 编程语言> > 使用JavaScriptNode(Web Audio API)制造冲动

使用JavaScriptNode(Web Audio API)制造冲动

作者:互联网

我正在使用Web Audio API,我正在尝试创建一个输出冲动的JavaScriptNode.也就是说,我想要一个节点,它将输出1后跟一大堆零,而不是其他任何东西.

我认为下面的代码是一种明智的方式来做到这一点.我将名为“timeForAnImpulse”的变量初始化为true,并使用此变量触发音频回调上的冲动输出.在回调中,我将“timeForAnImpulse”设置为false.

这似乎应该有效,但事实并非如此.我得到一个脉冲序列(每个缓冲区的起始处为1),而不是单个脉冲.知道我做错了什么吗?

<script type="text/javascript">

window.onload = init;

    function impulseNodeCB(evt){

        if(timeForAnImpulse){
            var buf = evt.outputBuffer.getChannelData(0);
            buf[0] = 1;
            timeForAnImpulse = false;
        }
    }

    var timeForAnImpulse = true;

    function init() {
        var context = new webkitAudioContext();
        impulseNode = context.createJavaScriptNode(2048,0,1);
        impulseNode.onaudioprocess = impulseNodeCB;
        impulseNode.connect(context.destination);   
    }

</script>

</head>

解决方法:

好的,我明白了!

我假设输出缓冲区evt.outputBuffer.getChannelData(0)在每次回调开始时用零初始化.事实并非如此.相反,它似乎从最后一次调用中保留了它的值.在else子句中明确归零缓冲区解决了这个问题.

<script type="text/javascript">

window.onload = init;

    function impulseNodeCB(evt){

        if(timeForAnImpulse){
            var buf = evt.outputBuffer.getChannelData(0);
            buf[0] = 1;
            timeForAnImpulse = false;
        } else {
            buf[0] = 0;
        }
    }

    var timeForAnImpulse = true;

    function init() {
        var context = new webkitAudioContext();
        impulseNode = context.createJavaScriptNode(2048,0,1);
        impulseNode.onaudioprocess = impulseNodeCB;
        impulseNode.connect(context.destination);   
    }

</script>

</head>

标签:javascript,web-audio
来源: https://codeday.me/bug/20190626/1292053.html