2012年11月29日 星期四

Web Audio API 簡單範例

這是Jimmy's papa整理出來的Web Audio API 簡單範例,可發出特定頻率的正弦聲波,
僅適用Chrome
        var context = new webkitAudioContext();
        var sampleRate = context.sampleRate;
        var node = context.createJavaScriptNode(128, 1, 1);
        var amplitude=0.8,frequency=300,currentSoundSample=0;

        node.onaudioprocess = function(e) { 
              var right = e.outputBuffer.getChannelData(0),
                  left = e.outputBuffer.getChannelData(1);

            var k = 2* Math.PI * frequency / sampleRate;
              for (var i = 0; i < right.length; ++i) {
                right[i] = left[i] = amplitude * Math.sin(k * currentSoundSample++);} 
            };

        function play() {
            frequency = parseFloat(document.getElementById("freq").value);
            currentSoundSample=0;
            node.connect(context.destination);
        }

        function pause() {
              node.disconnect();
        }

沒有留言:

張貼留言