Code Monkey home page Code Monkey logo

dancer.js's Introduction

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

dancer.js's People

Contributors

gr0uch avatar jsantell avatar padenot avatar ylambda avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dancer.js's Issues

using different runtime than soundmanager

Hello there,

I'd like to use your dancer in my project.
I wonder, has it been designed only for working with soundmanager? Is it possible to include a different runtime such as JWPlayer or JPlayer?

Thanks

Beat Detection

Hi there!

I'm trying to use dancer.js as a beat detector to count the amount of BPM of a song.

Using the single_song_demo example, i'm incrementing a variable on 'onbeat' event.
At 60 seconds I log the variable, but the result is not aligned with results given by BPM detection software.

What can I modify/tune? What am I doing wrong?

Thanks in advance.

Changing audio volume doesn't seem to work

using Webkit to test it.
i'm trying to change the volume of the audio:
dancer.audioAdapter.audio.volume=0.1
OR
dancer.audio.volume=0

doesn't seem to work.

a function to control the volume would be great.

Function to update beats frequency and threshold on-the-fly

beat.js Line 19:
SEARCH FOR: "Beat.prototype = {"
ADD AFTER:
setparam : function (frequency,threshold) {
this.frequency = frequency || options.frequency || [ 0, 10]; // 0, 10
this.threshold = threshold || options.threshold || 0.3; // 0.3
return this;
},

sounds glitches after change of audio src

I'm trying to use dancer with js music player, but when it changes source file everything sounds crappy. I've also tried to do this manually via chrome console in example file attached in dancer douwnload, but I've achieved the same crappy efect either when I've changed src during playback or when playback was paused. Is there any way to walk around this issue, like destroy and create new dancer? or maybe reload somehow.

Can't get any data in FF22

the kick not working, no any audio data
soundmanager v297 also got same problem, but it's works well if set preferFlash: true

----------------------------- update -------------------------------------
Found the reason, I commented some lines because the insecure operation, so the it can't get audio data. It backs work once uncomment the lines, but insecure operation appear again when playing local file.

Work on iOS / android?

Hi. Should this work on iOS or android? I am trying to view the demo on my iPhone and it does not seem to be working.

Uncaught Error(s) when playing live streams?

From line 48 of adapterWebAudio.js
this.audio.addEventListener( 'progress', function ( e ) {
if ( e.currentTarget.duration ) {
_this.progress = e.currentTarget.seekable.end( 0 ) / e.currentTarget.duration;
}
});

Causes an Uncaught IndexSizeError: Failed to execute 'end' on 'TimeRanges': The index provided (0) is not less than the object's length (0).

This occurs when I use sources like shoutcast and icecast.
This is fixable if you nest this condition if(e.currentTarget.seekable.length>0) inside the function.
This doesn't appear to be a problem in Chrome, it just runs through the error anyway. However, I'm guessing/hoping that a similar type of error for the mozilla adapter is preventing firefox from using live mp3 streams (it appears firefox can play and visualize local mp3's just fine).
Awesome project though I'm hooked on the demo.

Get Raw Complete Waveform Data

Hey, thank you for the amazing plugin.

This might already exist, but I couldn't find it. I am looking to process and store the waveform data for different audio tracks. I can get access to the current waveform data with .getWaveform(), but it is in real time. I'd love to be able to process a song in its entirety, store it in a JSON file, and then reference that data for my own purposes from the JSON data file, outside of dancer.js.

This would of course have to omit many samples to get a set of data that is manageable, and I was thinking that would be some sort of argument passed in. Such as, number of samples.

Does this exist? If not, is it in the works?

I've found command line tools that can get waveform data from files, but I'd rather keep it all in the browser. Thanks!

Support multiple audio types

Allow a string of a path to an audio source to be passed into Dancer constructor, as well as ordered audio types to check support

// Chrome would use /path/to/audio.mp3 while Firefox
// would use the first type that it supports and would load /path/to/audio.ogg
var dancer = new Dancer( "/path/to/audio", [ 'mp3', 'ogg' ] );

Prototyping arrays + dancer.js

I am trying to extend array functionality but it doesn't play well with dancer.js

for instance:

Array.prototype.somethingrandom = function() {

};

after this the kick event stop working due the error

TypeError: this.sections[i].condition is not a function @ dancer.js:191

this.sections[i].condition is undefined.I could check in the dancer.js if .condition is undefined but what cause this problem?

for testing I'am using the very basic code from example section.

[enhancement] [audio-data-api] Check Latest Firefox Mp3 playback support

After waiting for so long, Firefox will support mp3 (and H.264) with windows media foundation backend at the 2.0 release...
https://bugzilla.mozilla.org/show_bug.cgi?id=799315

"this feature is available, but not enabled on the current Windows Firefox Nightly Builds. Those currently using (http://nightly.mozilla.org/) the current Firefox 20 wishing to take advantage of this new feature need to enable via about:config tweak by setting media.windows-media-foundation.enabled to true."

i wounder if Dancer.js would work out of the box with after this.

Play two dancer instances at the same time

Hi,

Thanks for such awesome API.

I'm trying to play an audio with volume set to 0, then start a new instance that play the same audio onceAt X seconds, with volume set to 1.

I naively tried to call play method twice but it doesn't start a new instance.

Do you have any idea to make it properly ?

Browserify

  • Use browserify to generate build, create standalone and npm-able package
  • See if dependencies can be handled through npm dependencies

Insecure Operation in FF14

Get the following message in Firefox 14:
SecurityError: The operation is insecure.
this.signal[ i ] = ( e.frameBuffer[ 2 * i ] + e.frameBuffer[ 2 * i + 1 ] ) / 2;
adapterMoz.js, line 69

Documentation for Flash Fallback

Hoping to get some better documentation on how to implement the Flash Fallback functionality, as well as what functionality of Dancer can/cannot be used.

Thank you!

Demo fails in Fx 30

… and probably earlier and other engines. Quick inspection showed the JavaScriptNode as the (first) culprit. AFAIK, this has been renamed to ScriptProcessorNode.

Doesn't work with Webkit browsers (shoutcase/icecast streams)

Dancer won't work with Chrome at some cases,
problem is: i have no idea what's the difference.
all i know it this:

HOME PC: (Win7,Chrome‪21.0.1180.75 m‬) : playing music and beating.

WORK PC: (Win7,Chrome‪21.0.1180.75 m): playing music but not beating (no errors in console) - this.proc.onaudioprocess is never called.

FRIEND PC: (Win7,Chrome‪21.0.1180.75 m): not playing music nor beating (no errors in console) - this.proc.onaudioprocess is never called as well.

getTime() is incorrect in Webkit

Currently, Webkit's Web Audio implementation's context.currentTime returns the total elapsed time, not track time. Can wire the difference between timestamp on initial play

FF, Windows, SecurityError

Getting the following error on every "update":

FireFox14, Windows 8 64-bit, running normal FireFox.

SecurityError: The operation is insecure.
this.signal[ i ] = ( e.frameBuffer[ 2 * i ] + e.frameBuffer[ 2 * i + 1 ] ) / 2;

Investigate Using non-typed Arrays

Possibly non-typed arrays for all implementations, or just making a mini-shim using regular arrays on non-supported browsers (<= IE10)

Stopped working in Chrome as well

Dance.js is not working anymore neither in Chrome:
Uncaught TypeError: undefined is not a function dancer.js:32.
This makes it completely unusable.

ArrayBufferView size is not a small enough

RangeError: ArrayBufferView size is not a small enough positive integer (dancer.js:405) on Chrome.
http://news.ycombinator.com/item?id=4075063

Cannot reproduce?

Edit: Got in Opera, since it falls back to the Mozilla adapter, trying to create a new FFT, passing in NaN due to frameBuffer and channels being undefined, since buffer/channels/samplerate is not available in the big O. Perhaps break adapterMoz into an audio data api adapter, where if it supports audio data, great, otherwise, just play the audio track.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.