chrvadala / music-beat-detector

music-beat-detector is a library that analyzes a music stream and detects any beat. It can be used to control lights or any magic effect by the music wave.
MIT License
252 stars 25 forks source link
beat-detection javascript mp3 music nodejs

music-beat-detector

music-beat-detector is a library that analyzes a music stream and detects any beat. It can be used to control lights or any magic effect by the music wave.

npm Downloads Donate

Bundled with this library there are three components:

music-beat-detector

Example

const fs = require('fs')
const Speaker = require('speaker')
const createMusicStream = require('create-music-stream') //read this https://github.com/chrvadala/create-music-stream#faq
const {MusicBeatDetector, MusicBeatScheduler, MusicGraph} = require('music-beat-detector')

const musicSource = process.argv[2] //get the first argument on cli

const musicGraph = new MusicGraph()

const musicBeatScheduler = new MusicBeatScheduler(pos => {
  console.log(`peak at ${pos}ms`) // your music effect goes here
})

const musicBeatDetector = new MusicBeatDetector({
  plotter: musicGraph.getPlotter(),
  scheduler: musicBeatScheduler.getScheduler(),
})

createMusicStream(musicSource)
  .pipe(musicBeatDetector.getAnalyzer())
  .on('peak-detected', (pos, bpm) => console.log(`peak-detected at ${pos}ms, detected bpm ${bpm}`))
  .on('end', () => {
    fs.writeFileSync('graph.svg', musicGraph.getSVG())
    console.log('end')
  })

  .pipe(new Speaker())
  .on('open', () => musicBeatScheduler.start())

Usage

You can play any music sound supported by the library create-music-stream. Note: The beat detection performs better on mp3 files than YouTube video.

node example.js ./track.mp3
node example.js https://www.youtube.com/watch?v=qeMFqkcPYcg
node example.js https://www.youtube.com/watch?v=Zi_XLOBDo_Y
node example.js https://www.youtube.com/watch?v=n_GFN3a0yj0
node example.js https://www.youtube.com/watch?v=59Q_lhgGANc

Reference

new MusicBeatDetector(options)

Param Default Description
options.sensitivity 0.6 Response to the music wave (value from 0.5 to 1)
options.plotter - Instance of MusicGraph
options.scheduler - Instance of MusicBeatScheduler
options.minThreashold 1638 Peaks under this level are ignored (usually they're noise)
options.debugFilter false Stream the filtered music throught the lowpass filter (for debug purpose)

new MusicBeatScheduler(effectCallback)

new MusicGraph(secondWidth, secondHeight)

Contributors