cssAudio - Activefile-genericCSS - ActiveGeneric - ActiveHTML - ActiveImage - ActiveJS - ActiveSVG - ActiveText - Activefile-genericVideo - ActiveLovehtmlicon-new-collectionicon-personicon-teamlog-outoctocatpop-outspinnerstartv

Wave Shaping + Wave Folding

A Pen By Captain Anonymous

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

            
              <svg>
  <polyline id="scope" points="0,0,1024,1"/>
</svg>

<div class="sliders">
  <input type="range" id="folding" min="0" max="8" step="0.0001" value="0">
</div>
            
          
!
            
              body{
    margin:0;
    background-color:black;
}
html,body,svg{
    width:100%;
    height:100%;
}
polyline{
    stroke-width:1px;
    stroke:lime;
    fill:none;
}
.sliders{
  position:absolute;
  top:50%;
  background-color:rgba(124,142,112,0.25);
  width:100%;
}
input[type="range"]{
  width:100%;
}
            
          
!
            
              // polyfill
// window.AudioContext = window.AudioContext || window.webkitAudioContext;

//// create a sound studio
var studio = new AudioContext();
var speakers = studio.destination;

//// pick sound modules

///Volume
var volume = studio.createGain();

/// oscillator
var waveA = studio.createOscillator();
waveA.type = 'sine';
waveA.frequency.value = 55;
waveA.start(0);

// variable wave shape
var resolution = 100;
var real = new Float32Array(resolution);
var imag = new Float32Array(resolution);

var shapes = [
  {
    name:"sine",
    imag:Array.apply(0,Array(resolution)).map(function(callback,n){ return (n === 1) ? 1 : 0; })
  },
  {
    name:"triangle",
    imag:Array.apply(0,Array(resolution)).map(function(callback,n){ return ((n % 4 === 1) ? 1 : -0.5) / (n * n); })
  },
  {
    name:"ramp",
    imag:Array.apply(0,Array(resolution)).map(function(callback,n){ return 1/n; })
  },
  {
    name:"square",
    imag:Array.apply(0,Array(resolution)).map(function(callback,n){ return (((n + 1) % 2) ? 0 : 1) / n; })
  },
  {
    name:"pulse",
    imag:Array.apply(0,Array(resolution)).map(function(){ return 0.01; })
  }
];

/// wave folding filter
var folding = 0;
var waveFolder = studio.createScriptProcessor(4096,1,1);
waveFolder.onaudioprocess = function(event) {
  
  for (var channel = 0; channel < event.outputBuffer.numberOfChannels; channel++) {
    var inputData = event.inputBuffer.getChannelData(channel);
    var outputData = event.outputBuffer.getChannelData(channel);

    for(var sample = 0; sample < event.inputBuffer.length; sample++){
      var foldedOut = (1 + folding) * inputData[sample];
      while(foldedOut < -1 || foldedOut > 1){
          if(foldedOut > 1){
            foldedOut = 1 - foldedOut + 1;
          }
          if(foldedOut < -1){
            foldedOut = -1 - foldedOut - 1;
          }
       }

      outputData[sample] = foldedOut;
    }
  }
}

/// oscilloscope
var analyser = studio.createAnalyser();
analyser.fftSize = 2048;
var bufferLength = analyser.fftSize;
var dataArray = new Uint8Array(bufferLength);
analyser.getByteTimeDomainData(dataArray);
var i;
var scope = document.getElementById('scope');
var sliceWidth = window.innerWidth / bufferLength * 2.0;

function draw() {
  analyser.getByteTimeDomainData(dataArray);
  var points = [];
  var x = 0;
  var firstZero;
  for (i = 1; i < bufferLength; i++) {
    var y = dataArray[i] / 128 * window.innerHeight / 2;
    if (firstZero !== undefined) {
      points.push(x, y);
      x += sliceWidth;
    }
    if ((dataArray[i] >= 128 && dataArray[i - 1] < 128) ||
      (dataArray[i] <= 128 && dataArray[i - 1] > 128)) {
      if (firstZero === undefined && (dataArray[i] >= 128 && dataArray[i - 1] < 128))
        firstZero = i;
    }
  }
  mousey = false;
  scope.setAttributeNS(null, 'points', points.join(','));

  requestAnimationFrame(draw); //loop
}
draw(); //start loop

// wires
waveA.connect(waveFolder);
waveFolder.connect(volume);
volume.connect(speakers);
waveFolder.connect(analyser);

// controllers
var controllerX = 0.5;
var controllerY = 0.5;
document.addEventListener('mousemove', function(event) {
  
  // normalize X and multiply by count - 1
  controllerX = event.clientX/window.innerWidth * (shapes.length - 1);

  var from = Math.floor(controllerX);
  var to = Math.ceil(controllerX);

  // use each whole number in controllerX as a section
  lerp = controllerX % 1;
 
  imag = imag.map(function(callback,n){ return (1-lerp) * shapes[from].imag[n] + lerp * shapes[to].imag[n]; });
  waveform = studio.createPeriodicWave(real, imag);
  waveA.setPeriodicWave(waveform);

  //set pitch
  controllerY = 1 - event.clientY / window.innerHeight;
  var pitch = 40 * controllerY + 35;
  waveA.frequency.setTargetAtTime(pitch, studio.currentTime + 0.07, 0.1);

});

document.getElementById('folding').addEventListener('input', function(event){
  // set folding
  folding = parseFloat(this.value);
  console.log('folding',folding);
});

            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console