css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

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.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <div class="js-message message"></div>
<div class="recorder">
  <div class="waveform">
    <canvas class="js-canvas waveform__canvas"></canvas>
  </div>
</div>
            
          
!
            
              $blue-light: #49F1D5;
$blue: #2E748F;
$blue-dark: #153A49;

$white: #ffffff;
$black: #000000;

$red: #ED6A5F;

html {
  width: 100%;
  height: 100%;
  
  background: linear-gradient(180deg, $blue, $blue-dark); 
  
  font-size: 10px;
}


.waveform {
  position: relative;
  
  padding: 4rem 0;
  
  &__canvas {
    width: 100%;
    height: 40rem;
  }
}

.message {
  transtion: opacity .4s ease-in-out;
  padding: 1rem 2rem;
  
  background: $red;
  opacity: 0;
  
  font-size: 1.6rem;
  font-family: Helvetica, Arial, sans-serif;
  color: $white;
  line-height: 1.5;
  
  &--visible {
    opacity: 1;
  }
}
            
          
!
            
              // We'll store the value of te bars we want to draw in here
const bars = []

// An instance of AudioContext
const audioContext = new AudioContext();

// This will become our input MediaStreamSourceNode
let input = null;

// This will become our AnalyserNode
let analyser = null;

// This will become our ScriptProcessorNode
let scriptProcessor = null;

// Canvas related variables
const barWidth = 2;
const barGutter = 2;
const barColor = "#49F1D5";

let canvas = null;
let canvasContext = null;
let width = 0;
let height = 0;
let halfHeight = 0;
let drawing = false;

/**
 * Process the input of the ScriptProcessorNode.
 *
 * @param {audioProcessingEvent}
 */
const processInput = audioProcessingEvent => {  
    // Create a new Uint8Array to store the analyser's frequencyBinCount 
    const tempArray = new Uint8Array(analyser.frequencyBinCount);

    // Get the byte frequency data from our array
    analyser.getByteFrequencyData(tempArray);
    
    // Calculate the average volume and store that value in our bars Array
    bars.push(getAverageVolume(tempArray));

    // Render the bars
    renderBars(bars);
}

/**
 * Calculate the average value from the supplied array.
 *
 * @param {Array<Int>}
 */
const getAverageVolume = array => {    
    const length = array.length;
    let values = 0;
    let i = 0;

    // Loop over the values of the array, and count them
    for (; i < length; i++) {
        values += array[i];
    }

    // Return the avarag
    return values / length;
}

/**
 * Render the bars.
 */
const renderBars = () => {  
    if (!drawing) {
        drawing = true;

        window.requestAnimationFrame(() => {
            canvasContext.clearRect(0, 0, width, height);

            bars.forEach((bar, index) => {
                canvasContext.fillStyle = barColor;
                
                // Top part of the bar
                canvasContext.fillRect((index * (barWidth + barGutter)), (halfHeight - (halfHeight * (bar / 100))), barWidth, (halfHeight * (bar / 100)));

                // Bottom part of the bars
                canvasContext.fillRect((index * (barWidth + barGutter)), halfHeight, barWidth, (halfHeight * (bar / 100)));
            });

            drawing = false;
        });
    }
}

// Wait untill the page has loaded
(function() {
    // Get the canvas element and context
    canvas = document.querySelector('canvas');
    canvasContext = canvas.getContext('2d');

    // Set the dimensions
    width = canvas.offsetWidth;
    height = canvas.offsetHeight;
    halfHeight = height / 2;

    // Set the size of the canvas context to the size of the canvas element
    canvasContext.canvas.width = width;
    canvasContext.canvas.height = height;

    // Get the users microphone audio.
    navigator.mediaDevices.getUserMedia({  
        audio: true
    }).then(stream => {
        // Create the audio nodes
        input = audioContext.createMediaStreamSource(stream);
        analyser = audioContext.createAnalyser();
        scriptProcessor = audioContext.createScriptProcessor();

        analyser.smoothingTimeConstant = 0.3;
        analyser.fftSize = 1024;

        // Connect the audio nodes
        input.connect(analyser);
        analyser.connect(scriptProcessor);
        scriptProcessor.connect(audioContext.destination);

        // Add an event handler
        scriptProcessor.onaudioprocess = processInput;
    }, error => {
        // Something went wrong, or the browser does not support getUserMedia
    });
})();
            
          
!
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