audio-illustrator

Visualize audio using the Web Audio API

Usage no npm install needed!

<script type="module">
  import audioIllustrator from 'https://cdn.skypack.dev/audio-illustrator';
</script>

README

Audio Illustrator

Visualize audio easily by creating highly customizable illustrators.

Install

npm install audio-illustrator

Documentation

This package provides a simple class that helps receiving data from an audio, which can be used to create illustrators.
There are a lot of packages that give pre-made components which aren't very customizable, because you can only modify them by changing some attributes but you can't create a new one.

import Illustrator from 'audio-illustrator'

const illustrator = new Illustrator()

illustrator.connect(document.querySelector('#myAudio'))

const startDrawing = () => {
  illustrator.startLoop(startDrawing)
  // Get data for 18 items
  const audioData = illustrator.getData(18)
  // draw on canvas...
}

const stopDrawing = () => illustrator.stopLoop()

Illustrator({ waveform: boolean })

Contains all the methods. If waveform is true you get the current time-domain data, useful for creating waveform visualizations.
Otherwise you get the current frequency data, useful for creating visualizations with bars.

illustrator.connect(audio: HTMLAudioElement | HTMLVideoElement)

Creates the objects which store the data.

illustrator.disconnect()

Dismantles the objects which store the data.

illustrator.getData(items?: number)

Provides real-time frequency or time-domain analysis information (depending on the waveform parameter) for the amount of items you need (default is 128).

illustrator.startLoop(callback: FrameRequestCallback)

Starts the loop using requestAnimationFrame().

illustrator.stopLoop()

Stops the loop using cancelAnimationFrame().

illustrator.audioSrc

Represents the audio source.

illustrator.analyser

Represents the AnalyserNode

Usage with React

import * as React from 'react'
import Illustrator from 'audio-illustrator'

class App extends React.Component {
  illustrator

  state = { audioData: new Uint8Array(0) }

  componentDidMount() {
    this.illustrator = new Illustrator()
    illustrator.connect(this.audioRef)
  }

  componentWillUnmount() {
    illustrator.disconnect()
  }

  handlePlay = () => {
    illustrator.startLoop()

    this.setState({ audioData: illustrator.getData(18) })
    // draw on canvas
  }

  handlePause = () => {
    illustrator.stopLoop()
  }

  render() {
    return (
      <div>
        <audio
          ref={e => (this.audioRef = e)}
          onPlay={this.handlePlay}
          onPause={this.handlePause}
        />
      </div>
    )
  }
}