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>
<div class="controls">
  <button class="record" title="Record" id="toggle">
    Start Recording
    <svg viewBox="0 0 448 512" width="100" title="pause">
      <path d="M144 479H48c-26.5 0-48-21.5-48-48V79c0-26.5 21.5-48 48-48h96c26.5 0 48 21.5 48 48v352c0 26.5-21.5 48-48 48zm304-48V79c0-26.5-21.5-48-48-48h-96c-26.5 0-48 21.5-48 48v352c0 26.5 21.5 48 48 48h96c26.5 0 48-21.5 48-48z" />
    </svg>
  </button>
  <button class="stop" title="Stop Recording" id="stop">
    Stop Recording
    <svg viewBox="0 0 448 512" width="100" title="stop">
      <path d="M400 32H48C21.5 32 0 53.5 0 80v352c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V80c0-26.5-21.5-48-48-48z" />
    </svg>
  </button>
</div>
<audio controls></audio>  
<details class="recordings">
  <summary>Recordings</summary>
  <div class='recordings__empty-message'>No Recordings</div>
  <ul class="recordings__list">
  </ul>
</details>
              
            
!

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;
}

.recordings {
  font-family: sans-serif;
  color: hsl(0, 0%, 100%);
  width: 300px;
  padding: 1.25rem;
}

.recordings summary {
  font-weight: bold;
}

.recordings__empty-message {
  padding: 1rem;
  text-align: center;
}

.recordings__list {
  padding: 0.5rem 0;
  margin: 0;
}

.recordings__list > * + * {
  margin-top: 0.5rem;
}

.recordings__recording {
  display: flex;
  flex-direction: row;
  flex-gap: 0.125rem;
  gap: 0.125rem;
  align-items: center;
}

.recordings__recording span {
  flex: 1 1 0;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.recordings__recording:nth-of-type(even) {
  background: hsl(0, 0%, 25%);
}

.recordings__control {
  background: var(--bg);
  color: hsl(0, 0%, 100%);
  display: grid;
  place-items: center;
  height: 44px;
  width: 44px;
  flex: 0 0 44px;
  border-radius: 6px;
  cursor: pointer;
}

.recordings__control svg {
  fill: currentColor;
  width: 75%;
}

.recordings__play {
  --bg: hsl(120, 50%, 50%);
}
.recordings__delete {
  --bg: hsl(10, 50%, 50%);
}
.recordings__download {
  --bg: hsl(210, 50%, 50%);
}
              
            
!

JS

              
                import gsap from 'https://cdn.skypack.dev/gsap'

const TOGGLE = document.querySelector('#toggle')
const STOP = document.querySelector('.stop')
const AUDIO = document.querySelector('audio')
const LABEL = document.querySelector('label')
const CANVAS = document.querySelector('canvas')
const DRAWING_CONTEXT = CANVAS.getContext('2d')
const RECORDINGS_MESSAGE = document.querySelector('.recordings__empty-message')
const RECORDINGS_LIST = document.querySelector('.recordings__list')

let AUDIO_CONTEXT
let REPORT
let ANALYSER
let START_POINT
let AUDIO_BLOB

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

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

gsap.ticker.fps(CONFIG.fps)

let visualizing = false
let recorder
let timeline = gsap.timeline()

// use for visualization
const BARS = []
const METADATA = []
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 INITIAL_VALUE = { recordings: []}
const KEY = 'recordings'
const RECORDINGS = window.localStorage.getItem(KEY)
  ? JSON.parse(window.localStorage.getItem(KEY))
  : INITIAL_VALUE

const saveRecording = async () => {
  const reader = new FileReader()
  reader.onload = e => {
    const audioSafe = e.target.result
    const timestamp = new Date()
    const name = prompt('Recording name?')
    RECORDINGS.recordings = [
      ...RECORDINGS.recordings,
      {
        audioBlob: audioSafe,
        metadata: METADATA,
        name: name || timestamp.toUTCString(),
        id: timestamp.getTime(),
      },
    ]
    window.localStorage.setItem(KEY, JSON.stringify(RECORDINGS))
    renderRecordings()
    alert('Recording Saved')  
  }
  await reader.readAsDataURL(AUDIO_BLOB)
}

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)
  )
}

const reset = () => {
  AUDIO.src = null
  BARS.length = 0
  gsap.ticker.remove(REPORT)
  REPORT = null
  timeline.clear()
  padTimeline()
  drawBars()
}

const playRecording = (e) => {
  const idToPlay = parseInt(e.currentTarget.getAttribute('data-recording'), 10)
  reset()
  const RECORDING = RECORDINGS.recordings.filter(recording => recording.id === idToPlay)[0]
  RECORDING.metadata.forEach(bar => addBar(bar))
  REPORT = drawBars
  AUDIO.src = RECORDING.audioBlob
  AUDIO.play()
}

const downloadRecording = async (e) => {
  const idToDownload = parseInt(e.currentTarget.getAttribute('data-recording'), 10)
  const RECORDING = RECORDINGS.recordings.filter(recording => recording.id === idToDownload)[0]
  const BLOB = await (await fetch(RECORDING.audioBlob)).blob()
  const DOWNLOAD = document.createElement('a')
  DOWNLOAD.download = `Recording – ${RECORDING.name}`
  DOWNLOAD.href = URL.createObjectURL(BLOB)
  document.body.appendChild(DOWNLOAD)
  DOWNLOAD.click()
  DOWNLOAD.remove()
}

const deleteRecording = (e) => {
  if (confirm('Delete Recording?')) {
    const idToDelete = parseInt(e.currentTarget.getAttribute('data-recording'), 10)
    RECORDINGS.recordings = [...RECORDINGS.recordings.filter(recording => recording.id !== idToDelete)]
    window.localStorage.setItem(KEY, JSON.stringify(RECORDINGS))
    reset()
    renderRecordings()    
  }
}

const renderRecordings = () => {
  RECORDINGS_LIST.innerHTML = ''
  if (RECORDINGS.recordings.length > 0) {
    RECORDINGS_MESSAGE.style.display = 'none'
    RECORDINGS.recordings.reverse().forEach(recording => {
      const LI = document.createElement('li')
      LI.className = 'recordings__recording'
      LI.innerHTML = `<span>${recording.name}</span>`
      const BTN = document.createElement('button')
      BTN.className = 'recordings__play recordings__control'
      BTN.setAttribute('data-recording', recording.id)
      BTN.title = 'Play Recording'
      BTN.innerHTML = `<svg viewBox="0 0 448 512" width="100" title="play">
                         <path d="M424.4 214.7L72.4 6.6C43.8-10.3 0 6.1 0 47.9V464c0 37.5 40.7 60.1 72.4 41.3l352-208c31.4-18.5 31.5-64.1 0-82.6z" />
                       </svg>`
      LI.appendChild(BTN)
      const DOW = document.createElement('button')
      DOW.title = 'Download Recording'
      DOW.setAttribute('data-recording', recording.id)
      DOW.className = 'recordings__download recordings__control'
      DOW.innerHTML = `<svg viewBox="0 0 640 512" width="100" title="cloud-download-alt">
  <path d="M537.6 226.6c4.1-10.7 6.4-22.4 6.4-34.6 0-53-43-96-96-96-19.7 0-38.1 6-53.3 16.2C367 64.2 315.3 32 256 32c-88.4 0-160 71.6-160 160 0 2.7.1 5.4.2 8.1C40.2 219.8 0 273.2 0 336c0 79.5 64.5 144 144 144h368c70.7 0 128-57.3 128-128 0-61.9-44-113.6-102.4-125.4zm-132.9 88.7L299.3 420.7c-6.2 6.2-16.4 6.2-22.6 0L171.3 315.3c-10.1-10.1-2.9-27.3 11.3-27.3H248V176c0-8.8 7.2-16 16-16h48c8.8 0 16 7.2 16 16v112h65.4c14.2 0 21.4 17.2 11.3 27.3z" />
</svg>`
      LI.appendChild(DOW)
      const DEL = document.createElement('button')
      DEL.setAttribute('data-recording', recording.id)
      DEL.className = 'recordings__delete recordings__control'
      DEL.title = 'Delete Recording'
      DEL.innerHTML = `<svg viewBox="0 0 448 512" width="100" title="trash-alt">
                        <path d="M32 464a48 48 0 0 0 48 48h288a48 48 0 0 0 48-48V128H32zm272-256a16 16 0 0 1 32 0v224a16 16 0 0 1-32 0zm-96 0a16                                  16 0 0 1 32 0v224a16 16 0 0 1-32 0zm-96 0a16 16 0 0 1 32 0v224a16 16 0 0 1-32 0zM432 32H312l-9.4-18.7A24 24 0 0                                  0 281.1 0H166.8a23.72 23.72 0 0 0-21.4 13.3L136 32H16A16 16 0 0 0 0 48v32a16 16 0 0 0 16 16h416a16 16 0 0 0 16-                                  16V48a16 16 0 0 0-16-16z" />
                      </svg>`
      LI.appendChild(DEL)
      
      BTN.addEventListener('click', playRecording)
      DOW.addEventListener('click', downloadRecording)
      DEL.addEventListener('click', deleteRecording)
      RECORDINGS_LIST.appendChild(LI)
    })
  } else {
    RECORDINGS_MESSAGE.style.display = 'block'
  }
}
renderRecordings()

// 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)
}

const ANALYSE = stream => {
  AUDIO_CONTEXT = new AudioContext()
  ANALYSER = AUDIO_CONTEXT.createAnalyser()
  ANALYSER.fftSize = CONFIG.fft
  const SOURCE = AUDIO_CONTEXT.createMediaStreamSource(stream)
  const DATA_ARR = new Uint8Array(ANALYSER.frequencyBinCount)
  SOURCE.connect(ANALYSER)

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

  REPORT = () => {
    if (recorder && recorder.state === 'recording') {
      ANALYSER.getByteFrequencyData(DATA_ARR)
      const VOLUME = Math.floor((Math.max(...DATA_ARR) / 255) * 100)
      addBar(VOLUME)
      METADATA.push(VOLUME)
    }
    if (recorder || visualizing) {
      drawBars()
    }
  }
  gsap.ticker.add(REPORT)
}

const RECORD = () => {
  const toggleRecording = async () => {
    // If we aren't recording, we need to start a recording.
    if (!recorder) {
      visualizing = true
      STOP.style.display = 'flex'
      TOGGLE.style.setProperty('--active', 1)
      // Reset the timeline
      timeline.clear()
      // Reset the audio tag
      AUDIO.removeAttribute('src')
      AUDIO.removeAttribute('controls')
      TOGGLE.title = 'Pause Recording'
      const CHUNKS = []
      const MEDIA_STREAM = await window.navigator.mediaDevices.getUserMedia({
        audio: true,
      })

      recorder = new MediaRecorder(MEDIA_STREAM)
      // This signals stopping the recording. Only accessible via the "Stop" button.
      recorder.ondataavailable = async (event) => {
        // Update the UI
        TOGGLE.style.setProperty('--active', 0)
        STOP.style.display = 'none'
        TOGGLE.title = 'Start Recording'
        // Create the blob and show an audio element
        CHUNKS.push(event.data)
        AUDIO_BLOB = new Blob(CHUNKS, { type: 'audio/ogg' })
        AUDIO.setAttribute('src', window.URL.createObjectURL(AUDIO_BLOB))
        // Tear down after recording.
        recorder.stream.getTracks().forEach(t => t.stop())
        recorder = null
        // save the recording
        if (confirm('Save Recording?')) {
          saveRecording()
        }
      }
      recorder.start()
      timeline.play()
      ANALYSE(recorder.stream)
    } else {
      const RECORDING = recorder.state === 'recording'
      // Pause or resume recorder based on state.
      TOGGLE.style.setProperty('--active', RECORDING ? 0 : 1)
      timeline[RECORDING ? 'pause' : 'play']()
      recorder[RECORDING ? 'pause' : 'resume']()
    }
  }
  // Don't pause or restart it now. Start initially, pause, then make Stop available.
  toggleRecording()
}

TOGGLE.addEventListener('click', RECORD)


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

STOP.addEventListener('click', () => {
  if (recorder) recorder.stop()
  AUDIO.setAttribute('controls', true)
  AUDIO_CONTEXT.close()
  timeline.pause()
  SCRUB(START_POINT)
})

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

const UPDATE = e => {
  switch (e.type) {
    case 'play':
      gsap.ticker.add(REPORT)
      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)
      break
  }
}

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

              
            
!
999px

Console