preface

These days, I want to make a music player for my blog, collect and share my favorite music, and play it in the background while coding. However, I have thought that there are too few front-end things to do except to create a background, so I thought why not create a cool audio visualization of songs?

The main idea

Get audio interface, get audio data

Mozilla’s Audio API allows you to generate audio objects and manipulate them through this interface. This object is typically implemented through a special process: Source =>middle(sound processor, including reverb, filter, and the audio analyzer we need)=>terminal

Let me see the official picture:

)

Now, try the interface

// Get the media element used to generate the sound source
let audioElement = document.querySelector("audio")
AudioContext connections are restricted to cross domains
// note: for cross-domain detection, please enable local server test run (vscode download liveServer)
audioElement.crossOrigin = "anonymous"
let audioCtx = new AudioContext()
// Use the interface to get the parser
let analyser = audioCtx.createAnalyser()
// Get the audio source
let source = audioCtx.createMediaElementSource(audioElement)
// source=>middle
source.connect(analyser)
//middle=>termial
analyser.connect(audioCtx.destination)
// Set the Fourier transform parameter to set the analysis range
analyser.fftSize = 128
// Get the length of different audio quantities according to the range
let bufferLength = analyser.frequencyBinCount
// Generate an 8-bit array with an item and bufferLength
let dataArray = new Uint8Array(bufferLength)
// Import the frequency to the array
analyser.getByteFrequencyData(dataArray)
Copy the code

Finally, let’s play the music and continue to output the Array

audioElement.play()
setInterval((a)= > {
  let dataArray = new Uint8Array(bufferLength)
  analyser.getByteFrequencyData(dataArray)
  console.log(dataArray)
}, 1000)
Copy the code

Bingo!! Succeeded in getting the data

Connect audio data and import canvas drawing

The easiest way to make data correspond to graphics is to make each data representational as parameters of canvas graphics and make a simplest correspondence.

Generate a corresponding number of rectangles for each audio, and then arrange them in order, each with a height equal to the size of its audio.

Give it a try

/ / get canvas, canvarCtx
const canvas =document.querySelector('canvas')
const canvasCtx = canvas.getContext('2d')

// Draw once
function draw(){
  let  dataArray = new Uint8Array(bufferLength)
  analyser.getByteFrequencyData(dataArray)
  const bar_w = canvas.width / bufferLength;
  for (let i = 0; i < bufferLength; i++) {
      let bar_x = i * bar_w;
      let  bar_h = (dataArray[i] / 255) * canvas.height;
      let bar_y = canvas.height - bar_h
      canvasCtx.fillStyle = `green`; canvasCtx.fillRect(bar_x, bar_y, bar_w, bar_h); }}}Copy the code

Then, animate

function rockMusic() {
  requestAnimationFrame(rockMusic)
  analyser.getByteFrequencyData(dataArray)
  draw()
}
Copy the code

Synchronized development

Visualize data in various graphical styles

Make a wraparound bar

For a loop, set the loop origin, using canvasctx.translate and canvasctx.rorate

The effect

Make a spin ball

In order for this ball to move, you need to save it as an object, you need a container and then forEach

The effect

conclusion

This is simply a small profiler using the webAudioAPI, and I think there should be a lot more specialized things to mine for this thing; In addition, IN the visualization, I only use a simple canvas, interested students can use other libraries to design a variety of cool effects.

Finally, attach the source github.com/steve9II/.. …

Reference documentation

Developer.mozilla.org/en-US/docs/…