Pen Settings

HTML

CSS

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. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ add another resource

JavaScript

Babel includes JSX processing.

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

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

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.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <canvas></canvas>
<audio controls />  
              
            
!

CSS

              
                * {
  box-sizing: border-box;
}

body {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  flex-gap: 1rem;
  gap: 1rem;
  background: hsl(0, 0%, 20%);
}

canvas {
  height: 200px;
  width 300px;
  background: hsl(0, 0%, 10%);
  box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
}

.controls {
  position: relative;
}

.record,
.stop {
  border-radius: 50%;
  border: 4px solid white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0;
  height: 48px;
  width: 48px;
  background: none;
  position: relative;
  overflow: hidden;
  transform: translate(calc(var(--x, 0) * 1%), calc(var(--y, 0) * 1%)) scale(var(--scale, 1));
  transition: transform 0.1s;
}

.record {
  color: hsl(10, 80%, 50%);
}

.record svg {
  transform: scale(calc(5 - (var(--active, 0) * 4)));
  transform-origin: 20% 50%;
  transition: transform 0.1s;
}

.record,
.stop {
  &:hover {
    --scale: 1.1;
  }
  &:active {
    --scale: 0.9;
  }
}

.stop {
  display: none;
  position: absolute;
  left: 125%;
  border: none;
  background: none;
  top: 50%;
  --y: -50;
  color: hsl(0, 0%, 100%);
}

.stop svg
.record svg {
  height: 65%;
  fill: currentColor;
}

.reveal {
  cursor: pointer;
  position: fixed;
  top: 1rem;
  right: 1rem;
  height: 48px;
  width: 48px;
  display: grid;
  place-items: center;
  padding: 0;
  background: none;
  border: none;
}

.reveal svg {
  width: 100%;
  fill: hsl(0, 0%, 6%);
}

.reveal[aria-pressed="true"] svg:nth-of-type(1),
.reveal svg:nth-of-type(2) {
  display: none;
}

.reveal[aria-pressed="true"] svg:nth-of-type(2) {
  display: block;
}
              
            
!

JS

              
                import gsap from 'https://cdn.skypack.dev/gsap'
import { GUI } from 'https://cdn.skypack.dev/dat.gui'

const AUDIO = document.querySelector('audio')
const LABEL = document.querySelector('label')
const CANVAS = document.querySelector('canvas')
const DRAWING_CONTEXT = CANVAS.getContext('2d')

let AUDIO_CONTEXT
let REPORT
let ANALYSER
let START_POINT

CANVAS.width = CANVAS.offsetWidth
CANVAS.height = CANVAS.offsetHeight

const CONFIG = {
  fft: 64,
  show: true,
  duration: 0.1,
  fps: 24,
  barWidth: 4,
  barMinHeight: 0.04,
  barMaxHeight: 0.8,
  barGap: 2,
}

AUDIO.src = 'https://assets.codepen.io/605876/elevator-theme-tune.mp3'
AUDIO.crossOrigin = 'anonymous'

gsap.ticker.fps(CONFIG.fps)


let played = false
let timeline = gsap.timeline()

// use for visualization
const BARS = []
const fillStyle = DRAWING_CONTEXT.createLinearGradient(
  CANVAS.width / 2,
  0,
  CANVAS.width / 2,
  CANVAS.height
)
// Color stop is three colors
fillStyle.addColorStop(0.2, 'hsl(10, 80%, 50%)')
fillStyle.addColorStop(0.8, 'hsl(10, 80%, 50%)')
fillStyle.addColorStop(0.5, 'hsl(120, 80%, 50%)')

DRAWING_CONTEXT.fillStyle = fillStyle

const drawBar = ({ x, size }) => {
  const POINT_X = x - CONFIG.barWidth / 2
  const POINT_Y = CANVAS.height / 2 - size / 2
  DRAWING_CONTEXT.fillRect(POINT_X, POINT_Y, CONFIG.barWidth, size)
}

const drawBars = () => {
  DRAWING_CONTEXT.clearRect(0, 0, CANVAS.width, CANVAS.height)
  for (const BAR of BARS) {
    drawBar(BAR)
  }
}

const BAR_DURATION =
  CANVAS.width / ((CONFIG.barWidth + CONFIG.barGap) * CONFIG.fps)

const addBar = (volume = 0) => {
  const BAR = {
    x: CANVAS.width + CONFIG.barWidth / 2,
    // Note the volume is 0
    size: gsap.utils.mapRange(
      0,
      100,
      CANVAS.height * CONFIG.barMinHeight,
      CANVAS.height * CONFIG.barMaxHeight
    )(volume),
  }
  // Add to bars Array
  BARS.push(BAR)
  // Add the bar animation to the timeline
  // The actual pixels per second is (1 / fps * shift) * fps
  // if we have 50fps, the bar needs to have moved bar width before the next comes in
  // 1/50 = 4 === 50 * 4 = 200
  timeline.to(
    BAR,
    {
      x: `-=${CANVAS.width + CONFIG.barWidth}`,
      ease: 'none',
      duration: BAR_DURATION,
    },
    BARS.length * (1 / CONFIG.fps)
  )
}

// Given the canvas and the nodes Array, etc. Pad out the timeline and draw it.
const padTimeline = () => {
  // Doesn't matter if we have more bars than width. We will shift them over to the correct spot
  const padCount = Math.floor(CANVAS.width / CONFIG.barWidth)

  // Duplicate of what happens in REPORT needs moving and refactoring.
  for (let p = 0; p < padCount; p++) {
    addBar()
  }
  START_POINT = timeline.totalDuration() - BAR_DURATION
  // Sets the timeline to the correct spot for being added to
  timeline.totalTime(START_POINT)
}

let SOURCE

const ANALYSE = stream => {
  if (AUDIO_CONTEXT) return
  AUDIO_CONTEXT = new AudioContext()
  ANALYSER = AUDIO_CONTEXT.createAnalyser()
  ANALYSER.fftSize = CONFIG.fft
  SOURCE = AUDIO_CONTEXT.createMediaElementSource(AUDIO)
  const GAIN_NODE = AUDIO_CONTEXT.createGain()
  GAIN_NODE.value = 0.5
  const DATA_ARR = new Uint8Array(ANALYSER.frequencyBinCount)
  GAIN_NODE.connect(AUDIO_CONTEXT.destination)
  SOURCE.connect(GAIN_NODE)
  SOURCE.connect(ANALYSER)


  // Reset the bars and pad them out...
  if (BARS && BARS.length > 0) {
    BARS.length = 0
    padTimeline()
  }

  REPORT = () => {
    if (!AUDIO.paused || !played) {
      ANALYSER.getByteFrequencyData(DATA_ARR)
      const VOLUME = Math.floor((Math.max(...DATA_ARR) / 255) * 100)
      addBar(VOLUME)
      drawBars()  
    }
  }
  gsap.ticker.add(REPORT)
}

const SCRUB = (time = 0, trackTime = 0) => {
  gsap.to(timeline, {
    totalTime: time,
    onComplete: () => {
      AUDIO.currentTime = trackTime
      if (!played) {
        played = true
        gsap.ticker.remove(REPORT)
        gsap.ticker.add(drawBars) 
      }
    },
  })
}

// INITIAL RENDERING so we don't have a black box.
padTimeline()
drawBars()

const UPDATE = e => {
  switch (e.type) {
    case 'play':
      if (!played) ANALYSE()
      timeline.totalTime(AUDIO.currentTime + START_POINT)
      timeline.play()
      break
    case 'seeking':
    case 'seeked':
      timeline.totalTime(AUDIO.currentTime + START_POINT)
      break 
    case 'pause':
      timeline.pause()
      break
    case 'ended':
      timeline.pause()
      SCRUB(START_POINT, 0)
      break
  }
}

// Set up AUDIO scrubbing
['play', 'seeking', 'seeked', 'pause', 'ended'].forEach(event => AUDIO.addEventListener(event, UPDATE))

              
            
!
999px

Console