質問

I'm working with the Web Audio API, and I'm trying to make a JavaScriptNode that outputs an impulse. That is, I want a node that will output a 1 followed by a whole bunch of zeros, and nothing else.

I thought the code below would be a sensible way to do this. I initialize a variable called "timeForAnImpulse" to true and use this variable to trigger an impulsive output on the audio callback. In the callback, I then set "timeForAnImpulse" to false.

This seems like it should work, but it doesn't. Instead of a single impulse, I get an impulse train (a 1 at the start of each buffer). Any idea what I'm doing wrong?

<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>
役に立ちましたか?

解決

Ok, I figured it out!

I had assumed that the output buffer evt.outputBuffer.getChannelData(0) was initialized with zeros at the start of each callback. It isn't. Instead, it seems to retain its values from its last invocation. Explicitly zeroing the buffer in an else clause solved the problem.

<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>
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top