• Stars
    star
    2,102
  • Rank 21,865 (Top 0.5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 12 years ago
  • Updated about 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

high-level audio API, designed to make sweet visualizations

dancer.js

dancer.js is a high-level audio API, usable with both Mozilla's Audio Data API and Web Audio API with flash fallback, designed to make sweet visualizations.

http://jsantell.github.com/dancer.js

v0.4.0 (2/2/2014)

Features

  • Use real-time audio waveform and frequency data and map it to any arbitrary visualization
  • Use Dancer to get audio data from any preexisting audio source
  • Leverage kick detection into your visualizations
  • Simple API to time callbacks and events to any section of a song
  • Supports Web Audio (webkit/mozilla), Audio Data (mozilla) and flash fallback (v9+)
  • Extensible framework supporting plugins and custom behaviours

Dancer Instance Methods

Setup

  • load( source ) specifies the audio source for the dancer instance. source can either be an audio element, or an object with a src property and an optional codecs array. While the audio element source is recommended to use with other players, if you specify a config object, the src property can either be a string of the audio path, or a string of the audio path, without the file extension, if you specify a codec array to work across multiple audio implementations. Examples of input:
  var dancer = new Dancer();

  // Using an audio object
  var a = new Audio();
  a.src = 'somesong.mp3';
  dancer.load( a );

  // Using an audio element on the page
  dancer.load( document.getElementsByTagName('audio')[0] );

  // Using a config object and you only have one encoding
  dancer.load({ src: 'somesong.mp3' });

  // Using a config object, and you have an ogg and mp3 version
  dancer.load({ src: 'somesong', codecs: [ 'ogg', 'mp3' ]});

Controls

All controls return this. If provided an audio element as the source, one can also control the audio through that, or can access the audio element in the audio property on the dancer instance.

  • play() plays the audio and begins the dance.
  • pause() pauses the madness.
  • setVolume() sets the player's current volume.

Getters

  • getVolume() returns a normalized value (0 to 1) of the current volume.
  • getTime() returns the current time.
  • getProgress() returns the downloading progress as a float from 0 to 1.
  • getWaveform() returns the waveform data array (Float32Array(1024))
  • getSpectrum() returns the frequency data array (Float32Array(512)).
  • getFrequency( freq [, endFreq ] ) returns the magnitude of a frequency or average over a range of frequencies.
  • isLoaded() returns a boolean value for the dancer instance's song load state.
  • isPlaying() returns a boolean value indicating whether the dancer instance's song is currently playing or not.

Sections

All section methods return this (CHAIN IT UP) and callbacks executed with this referencing the dancer instance.

  • after( t, callback ) fires callback on every frame after time t.
  • before( t, callback ) fires callback on every frame before time t.
  • between( t0, t1, callback ) fires callback on every frame between time t0 and t1.
  • onceAt( t, callback ) fires callback once at time t.

Bindings

Basic pub/sub to tie into the dancer instance. update and loaded are predefined events called within the framework that are published on every frame (update) and on audio file load (loaded). All callbacks executed with this referencing the dancer instance.

  • bind( name, callback ) subscribes a callback of name. Can call this method several times to bind several callbacks of the same name.
  • unbind( name ) unsubscribes all callbacks of name.
  • trigger( name ) calls all callbacks of name.

Kick

Kicks are detected when the amplitude (normalized values between 0 and 1) of a specified frequency, or the max amplitude over a range, is greater than the minimum threshold, as well as greater than the previously registered kick's amplitude, which is decreased by the decay rate per frame.

  • createKick( options ) creates a new kick instance tied to the dancer instance, with an options object passed as an argument. Options listed below.
    • frequency the frequency (element of the spectrum) to check for a spike. Can be a single frequency (number) or a range (2 element array) that uses the frequency with highest amplitude. Default: [ 0, 10 ]
    • threshold the minimum amplitude of the frequency range in order for a kick to occur. Default: 0.3
    • decay the rate that the previously registered kick's amplitude is reduced by on every frame. Default: 0.02
    • onKick the callback to be called when a kick is detected.
    • offKick the callback to be called when there is no kick on the current frame.

Dancer Static Methods

  • addPlugin( name, fn ) registers a plugin of name with initiation function fn -- described in more detail below
  • isSupported() returns a string of webaudio, audiodata or flash indicating level of support. Returns an empty string if the browser doesn't support any of the methods. Can also return null when browser does not support typed arrays.
  • canPlay( type ) returns either true or false indicating whether the browser supports playing back audio of type type, which can be a string of 'mp3', 'ogg', 'wav', or 'aac'.
  • setOptions( options ) takes a set of key-value pairs in an object for options. Options below.
  • version not a method, but a property of the Dancer object to return a string of the current Dancer version

Dancer Options

  • flashSWF The path to soundmanager2.swf. Required for flash fallback.
  • flashJS The path to soundmanager2.js. Required for flash fallback.

Kick Instance Methods

These methods can be called on a kick instance to turn on and off the registered callbacks

  • on() turns on the kick instance's callbacks and detections
  • off() turns off the kick instance's callbacks and detections
  • set( options ) can pass in an object literal with the 5 kick options, similar to creating a new kick option

Example

For simple examples, check out the examples/ folder -- both the FFT and waveform examples are straight forward, leveraging the corresponding plugins for visualizations.

  // To enable flash fallback, specify the paths for the flashSWF and flashJS
  Dancer.setOptions({
    flashJS  : '../../lib/soundmanager2.js',
    flashSWF : '../../lib/soundmanager2.swf'
  });

  var
    audio  = document.getElementsByTagName('audio')[0],
    dancer = new Dancer(),
    kick = dancer.createKick({
      onKick: function ( mag ) {
        console.log('Kick!');
      },
      offKick: function ( mag ) {
        console.log('no kick :(');
      }
    });

  // Let's turn this kick on right away
  kick.on();

  dancer.onceAt( 10, function() {
    // Let's set up some things once at 10 seconds
  }).between( 10, 60, function() {
    // After 10s, let's do something on every frame for the first minute
  }).after( 60, function() {
    // After 60s, let's get this real and map a frequency to an object's y position
    // Note that the instance of dancer is bound to "this"
    object.y = this.getFrequency( 400 );
  }).onceAt( 120, function() {
    // After 120s, we'll turn the kick off as another object's y position is still being mapped from the previous "after" method
    kick.off();
  }).load( audio ); // And finally, lets pass in our Audio element to load

  dancer.play();

Requirements

HTML5 Playback with Web Audio or Audio Data Chrome and Firefox are both supported out of the box -- other browsers will need to leverage the flash fallback until either of these APIs are implemented.

Safari 6 Web Audio API While Safari 6 does have the Web Audio API, it doesn't currently support processing audio from a media element source. Falls back to flash.

To enable flash You must set Dancer's defaults for flashSWF with the path to the soundmanager2.swf and flashJS to the path to soundmanager2.js, both found in lib/. Flash player 9 is required, and you must provide an mp3 option. Waveform data in Flash is a 1024 Float32Array, but only the first 512 elements have values due to flash's computeSpectrum method.

Uint32Array and Float32Array are required Include a shim if you'd like to support browsers that do not have these typed arrays.

Dependencies

  • dsp.js - A subset of dsp.js (fft) is used for Fast Fourier Transformations ( Included in packaged Dancer )
  • flash_detect - flash detect is used for immediate flash detection ( Included in packaged Dancer )
  • soundmanager2 - soundmanager2 is used for flash fallback ( found in lib/, asynchronously loaded )

Extending/Plugins

You can extend the Dancer prototype by calling the static method addPlugin( name, fn ), which extends the Dancer prototype. A Dancer instance then can call the function provided in its context and subscribe to a preexisting event like update, or make your own. Look in the plugins/ directory for examples.

Development

This project uses grunt to build and jasmine for testing. Run grunt from the project root to lint and build files. A CLI for testing would be awesome, but Mozilla and WebKit implementations differ greatly -- go to spec/index.html in Mozilla/WebKit browsers to test. All tests should pass in Chrome and Firefox (95% of the time) -- Flash implementations are much more annoying, need to have cleaned up tests.

Change Logs

v0.4.0 (1/28/2014)

  • Update to work with new Web Audio function names. Dancer now uses Web Audio in Firefox 25+.

v0.3.2 (9/29/2012)

  • Change build process to using grunt.js

v0.3.1 (8/13/2012)

  • Renamed beat to kick for future, true kick-detection
  • Added getProgress() to track progress of downloaded audio file (#20)
  • Added setVolume() and getVolume() as instance methods (#21)
  • Added set() method to kick instance (#16), fixed ability to assign 0 to a kick attribute

v0.3.0 (8/9/2012)

  • Added ability to provide an audio element as a source -- can control audio via the element, or accessed through instance's audio property, or through Dancer's helper controls (play, pause)
  • Pulled out loading from the constructor to the instance method load. Can use the above mentioned audio element, or a config object with path information.
  • Changed instance method stop to pause, to be more in line with audio elements
  • Added example of using the audio element in examples/audio\_element.

v0.2.1 (6/16/2012)

  • Added getWaveform() method and a corresponding visualization for waveforms

v0.2.0 (6/14/2012)

  • Added flash support with soundmanager2 -- flash_detect now included in build
  • Added static methods isSupported, canPlay and setOptions
  • Added multiple audio codecs support (#7)
  • Added a new simple FFT examples, both examples having feature detection and controls (#10)
  • Fixed several Webkit bugs (#4, #8)

v0.1.0 (6/3/2012)

  • Initial Web Audio/ Audio Data release

More Repositories

1

poet

A node.js blog engine
JavaScript
602
star
2

THREE.IK

inverse kinematics for three.js
JavaScript
457
star
3

node-zip-dir

Zips up directories into buffers or saves to disk
JavaScript
47
star
4

ImpactStorage

Local Storage plugin for ImpactJS
JavaScript
35
star
5

s3-stream-upload

A writable stream which uploads to Amazon S3 using the multipart file upload API.
JavaScript
26
star
6

mini-webgl

Mini toy WebGL library
JavaScript
23
star
7

ogg.js

ogg vorbis decoder in JavaScript
JavaScript
21
star
8

node-json-front-matter

Extract JSON front matter from strings and files
JavaScript
20
star
9

experiments

audio/VR/AR/GL experiments for the web
JavaScript
19
star
10

dsp-with-web-audio-presentation

Presentation for JSConf 2014, "Signal Processing with the Web Audio API"
CSS
19
star
11

web-audio-automation-timeline

Timeline utility for calculating values of web audio automation parameters over time.
JavaScript
17
star
12

pcm-transform

Transformation stream for PCM data
JavaScript
17
star
13

go-githubstream

Fetch commits from a GitHub repository periodically
Go
17
star
14

allen

Utilities for the Web Audio API
CoffeeScript
16
star
15

electron-ipc-mock

Mock channels for Electron's IPC communication
JavaScript
14
star
16

engineering-management-resources

A collection of links of engineering manager resources
13
star
17

web-audio-instrumentation

Instruments functions in the Web Audio API
JavaScript
12
star
18

presentr

jQuery Plugin for Presentations
JavaScript
10
star
19

dial

A UI dial component
JavaScript
9
star
20

web-audio-api-bugs

Examples to recreate issues in Web Audio API implementations
8
star
21

mongoose-schema-model

Small model definitions (MongooseDB style) for composable use in other environments
JavaScript
8
star
22

buffer-queue

fast buffer storage
JavaScript
8
star
23

gl-preserve-state

JavaScript
7
star
24

backbone-promised

Wraps up Backbone's XHR methods into a consistent promisable API
JavaScript
7
star
25

aframe-react-components

React components for aframe primitives for aframe-react.
JavaScript
6
star
26

unburyme-rails

Ruby
6
star
27

AcidCupcakeColourScheme

A vibrant, dark and obnoxiously awesome colour scheme for text editors and terminals.
Vim Script
6
star
28

web-ar-samples

A collection of samples using AR features in the WebXR Device API
JavaScript
6
star
29

three-simple-fp-controls

Simple, boring, first person controls for three.js
JavaScript
5
star
30

GhostTrain

Client-side router in the spirit of Express for mock data, development and demos.
JavaScript
5
star
31

chrome-api-definitions

Definition generator for Chrome Platform APIs
C++
5
star
32

mock-s3

In-memory mock S3 lib
JavaScript
5
star
33

webvr-demos

HTML
5
star
34

mozilla-tree-status

Firefox Addon for displaying the status of the integration trees
JavaScript
4
star
35

beatbox

beatbox
JavaScript
4
star
36

sort

Sorting algorithms in JavaScript
JavaScript
4
star
37

archived_dotfiles

~
Vim Script
4
star
38

jquery-gh-repo

jQuery plugin for grabbing GitHub repo information (watchers, forks) and displaying them
JavaScript
4
star
39

node-cfx

programmatically use cfx with node.js
JavaScript
4
star
40

three-app

Personal generalized app structure for THREE apps, hosted on npm as @jsantell/three-app
JavaScript
4
star
41

jquery-twitch

jQuery plugin for making links dance anaglyph-style on hover
JavaScript
4
star
42

interpolate-color

A simple color interpolator component
JavaScript
4
star
43

v8-api-search

Search the V8 API from the browser's address bar.
JavaScript
4
star
44

sprout-deploy

Deploy server for AWS ElasticBeanstalk via REST
JavaScript
3
star
45

spectron-keys

Accelerator mappings for Electron commands to Spectron/WebDriver key codes.
JavaScript
3
star
46

event-target

Simple EventTarget implementation.
JavaScript
3
star
47

swag-mvc

connecting your models and routes in node.js
JavaScript
3
star
48

node-link-injection

Parse text for keywords and replace with links for documentation
JavaScript
3
star
49

SARS-CoV-2-genome

SARS-CoV-2 genome
3
star
50

node-video-splash

JavaScript
3
star
51

web-audio-tools-presentation

Web Audio tools presentation for JSFest Berlin's Web Audio Hack Day
CSS
3
star
52

s3-waveform

Generate and store waveform data given an s3 key to an audio file via streams
JavaScript
3
star
53

codevember-2017

Codevember 2017
JavaScript
2
star
54

devtools-branding

2
star
55

streambuffers

Buffer-based readable and writable streams
JavaScript
2
star
56

overview-of-dancer.js

slides for philly.js talk on dancer.js
JavaScript
2
star
57

three-components

Personal collection of three.js objects, utilities and helpers.
JavaScript
2
star
58

button

A UI on/off button component
JavaScript
2
star
59

rotate

UI component for CSS3 rotations
JavaScript
2
star
60

node-firefox-get

Grabs Firefox package URLs. Deprecated, please use https://github.com/mozilla-b2g/mozilla-get-url
JavaScript
2
star
61

stream-request

Middleware for parsing data from a multipart/form-data request and putting data as streams onto a connect request.
JavaScript
2
star
62

immersive-web-weekly

DEPRECATED: go to https://github.com/immersive-web/immersive-web-weekly
HTML
2
star
63

jp-rocketjump

Prototype of jumpstarting Mozilla add-on development
JavaScript
2
star
64

metalsmith-plugins

A personal collection of metalsmith plugins.
JavaScript
1
star
65

sprout

Server for handling AWS EB environments and deployments
JavaScript
1
star
66

properties-loader

Loader for .properties files for Webpack
JavaScript
1
star
67

graphics-node

graphics computation for node from gradschool
JavaScript
1
star
68

tiny-time

Tiny DSL for creating Dates.
JavaScript
1
star
69

web-audio-tools

web audio tools
JavaScript
1
star
70

eb-mock

Mock API for AWS ElasticBeanstalk
JavaScript
1
star
71

dotfiles

Python
1
star
72

arkitekt

Boilerplate structure for webapps my style.
JavaScript
1
star
73

webvr-content-workshop-slides

Slides for W3C Workshop for WebVR Authoring
1
star
74

backbone-model-definition

JavaScript
1
star
75

text-query

Generate simple boolean text queries
JavaScript
1
star
76

web-audio-tools-2015

Web Audio Tools talk for WAC 2015
CSS
1
star
77

js1k-love

js1k, Love
JavaScript
1
star
78

three-orbit-controls

Personal fork of THREE.OrbitControls hosted on npm as @jsantell/three-orbit-controls
JavaScript
1
star
79

mentat-explorer

An in-browser IDE for exploring a Mentat database
JavaScript
1
star
80

css-properties-and-values-tests

Personal test cases for testing browser support for CSS Properties and Values API Level 1
JavaScript
1
star
81

jetpack-soundcloud-streamer

JavaScript
1
star
82

LiquidData2013

Liquid Data 2013
JavaScript
1
star
83

browser-rendering-links

1
star
84

daftpunktocat

web audio'd daftpunkocat
JavaScript
1
star
85

loadio

A small loader for asynchronously loading JS and CSS files independently, in series or parallel to prevent blocking
JavaScript
1
star
86

node-request-extend

Jumps in your middleware and extends route requests with references
JavaScript
1
star
87

js-hack-night

collection of resources for js hack night
JavaScript
1
star
88

cache-per-frame

Cache the result of a function once per frame
JavaScript
1
star
89

fx-devtools-bot

Bot that tweets for Firefox Dev Tools on every landed patch.
Go
1
star
90

addon-repack-tester

Tests a before and after of a repack of a Firefox addon for differences
JavaScript
1
star
91

string-gauges

Data mapping types of guitar strings by gauge to their unit weight
JavaScript
1
star
92

browser-dance-party-slides

Slides for "Browser Dance Party" talk at HTML5 Dev Conf
JavaScript
1
star