• Stars
    star
    200
  • Rank 188,791 (Top 4 %)
  • Language
    JavaScript
  • Created almost 13 years ago
  • Updated over 11 years ago

Reviews

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

Repository Details

A javascript library for audio output

sink.js

sink.js is a javascript library dedicated for audio output. Features include buffer fill callbacks, synchronous write, asynchronous write, ring buffers and recording. Currently supported platforms are Firefox 4+ and Chrome with Web Audio API enabled in about:flags. Additional platforms, such as a flash fallback can be added as plugins, but are currently not featured, nor will ever be enabled by default. For a platform to be added as enabled by default, it needs to be reliable in terms of latency and stability. Flash fallbacks – for example – cannot offer this kind of reliability and the sound will always be flaky at best.

Basic usage

To create a sink, the following function is available:


var sink = Sink([callback=null], [channelCount=2], [preBufferSize=4096], [sampleRate=44100])

Currently, it is recommended to check that you are actually running at the sample rate that you specified, so when you create a sink, get the samplerate reference always from its .sampleRate property.

The callback is fed with two arguments, the buffer to fill and the channel count of the buffer. For example, to play back stereo noise, you can do the following:

var sink = Sink(function(buffer, channelCount){
	var i;
	for (i=0; i<buffer.length; i++){
		buffer[i] = Math.random() - 0.5;
	}
});

Note that buffer is interleaved and therefore the samples should be written as :

[
    channel1, channel2, ... channelN,	// frame 1
    channel1, channel2, ... channelN,	// frame 2
    ...	                                // ...
]

For example, to play back a 440Hz sine wave in stereo, you can do :

var k, v, n = 0;
var sink = Sink(function(buffer, channelCount){
	for (var j=0; j<buffer.length; j+=2, n++) {
        	v = Math.sin(k*n);
        	buffer[j] = v;
        	buffer[j+1] = v;
    	}
}, 2); // 2 channels ... which is already the default

k = 2*Math.PI*440/sink.sampleRate;

Note also that the length of the buffer can vary, it will however always be less than preBufferSize. If you need control over buffer's length, check-out [proxies][proxy].

To bring the sink to a force stop, you can use the .kill() method. But so far, this doesn't work in Chrome, and the Chrome's AudioContext can't be taken down. This will be fixed as soon as possible. Also, beware of creating multiple sinks to avoid unexpected results.

Buffer writing API

As an alternative to the callback API, you can directly write sound to the buffers with .write(buffer, [delay=undefined]) method. The default writing mode is "async" where the specified buffer will be mixed with existing data. If a delay is not specified, the system will automatically create a delay to try to compensate the latency. The delay is specified as number of samples.

Another mode of writing is "sync". You can set this by changing your sink's .writeMode property to "sync". In the "sync" write mode, the delay is disregarded and instead all written buffers will be appended right after the previous one has been exhausted. To get the current sample offset in the "sync" write mode, you can use the .getSyncWriteOffset() method.

Beware of writing zero-length buffers, as they will induce NaNs to your buffers. This can be a bad thing especially if written in the "sync" mode and combined with some effects processing in a callback.

Proxy

[proxy]:

Proxy is a thin-wrapper around the basic sink, allowing you to control the size of the buffer received by the callback.

To create a proxy, use the following function:


var proxy = Sink.createProxy([bufferSize=4096])

For example, to play back a 440Hz sine wave in stereo, you can do :

var bufferSize = 4096, sink = Sink();
var proxy = sink.createProxy(bufferSize);
proxy.on('audioprocess', function(buffer, channelCount){
	for (var j=0; j<bufferSize; j+=2, n++) {
        	v = Math.sin(k*n);
        	buffer[j] = v;
        	buffer[j+1] = v;
    	}
});

Recording

Recording can be done by creating an instance of the recording, like this:

var recording = sink.record();

// And when you want to stop recording:

recording.stop();

// To join the recording into a single buffer:

var buffer = recording.join();

Ring buffer

Here's an example how to use the ring buffer:

// Enable & create the ring buffer

sink.ringBuffer = new Float32Array(sink.sampleRate * sink.channelCount);

// Get or modify the current offset of the ring buffer.

console.log(sink.ringOffset);

That would create a ring buffer of the length of a single second, and you can manipulate that anyway you want, and use it together with callbacks and / or writing.

Projects using sink.js

  • aurora.js A JS-powered video and audio playback framework.
  • Audiolet A comphrehensive, graph based audio synthesis / composition library for JS.
  • audiolib.js A full-fletched audio synthesis / processing framework.

License

sink.js is released under MIT license.

More Repositories

1

trine

A utility library for modern JavaScript.
JavaScript
1,416
star
2

audiolib.js

audiolib.js is a powerful audio tools library for javascript.
JavaScript
670
star
3

html5Preloader.js

A javascript library to preload all kinds of content, be it text, xml, audio, video or image, with simple syntax.
JavaScript
228
star
4

react-no-jsx

A pure JS alternative to JSX
JavaScript
69
star
5

babel-plugin-operator-overload

Babel plugin for overloading operators
JavaScript
67
star
6

pcmdata.js

A javascript library to read / write .wav pcm data files
JavaScript
42
star
7

node-dsp

An implementation of the DSP API
CoffeeScript
38
star
8

binary.js

Provides a very fast and robust interface for binary conversions in JavaScript
JavaScript
33
star
9

gulp-awspublish-router

A router for defining file-specific rules with gulp-awspublish
JavaScript
29
star
10

htmlentities.js

A minimal html entities decoder/encoder using DOM.
JavaScript
26
star
11

jQuery.grab

A port of Jin's grab gesture.
JavaScript
21
star
12

node-progress-bar

An STDOUT progress bar for NodeJS
JavaScript
20
star
13

merry-go-round

Merry-go-Round is a React-based component library for building amazing carousels!
JavaScript
19
star
14

polyfill-service-webpack

A webpack plugin for polyfill.io.
JavaScript
18
star
15

eslint-plugin-no-implicit-side-effects

ESLint plugin for requiring side effects to be explicit.
JavaScript
18
star
16

BrainScript

BrainScript is a scripting language that is a subset of JavaScript and inspired by Urban MΓΌller's brainfuck.
18
star
17

gulp-spa

Define your build sources in HTML.
JavaScript
16
star
18

mike.js

JavaScript
14
star
19

web-midi-test-suite

A test suite for Web MIDI API
JavaScript
14
star
20

fft.js

A Fast Fourier Transform in JavaScript
JavaScript
13
star
21

node-cubeb

Node module for libcubeb
C++
13
star
22

vectorizer.js

A JS library for raster->vector
JavaScript
13
star
23

weakbind

Memoized bind for higher performance.
JavaScript
10
star
24

slogdriver

Stackdriver Logging / GCP Cloud Logging handler for the go 1.21 slog package.
Go
10
star
25

react-mistyped-props

Warnings for mistyped props in your React components.
JavaScript
10
star
26

simplesynth

A simple synth example for Firefox 4 Audio API
JavaScript
9
star
27

atom-npm-plus

npm integration for atom
JavaScript
8
star
28

src.js

Sample Rate Conversion for JS
JavaScript
7
star
29

btoa-atob

Command line utility to convert files to base64 and vice versa.
JavaScript
7
star
30

http.js

A HTTP utilities library for client-side applications.
JavaScript
5
star
31

macnjs

C Preprocessor for JS (or anything, really)
C
5
star
32

kakku

A backend agnostic cache layer for node.js
JavaScript
5
star
33

jin.js

A lightweight javascript library / framework
JavaScript
5
star
34

virtual-midi-keyboard

A virtual HTML5 MIDI keyboard
JavaScript
5
star
35

canvas-history.js

Binds an easy undo/redo API to Canvas 2D Drawing Context.
JavaScript
5
star
36

node-blessings

node.js port of python's blessings
JavaScript
5
star
37

asifier

JavaScript
4
star
38

dotfiles

My workflow, probably nothing you'd care about.
Vim Script
4
star
39

midinode

A NodeJS module providing cross-platform JS bindings for MIDI device control.
C++
4
star
40

grunt-pack

Packaging tasks for Grunt
JavaScript
4
star
41

setImmediate.js

A small shim for the setImmediate() that creates a callback similar to process.nextTick() on node.js
JavaScript
4
star
42

sweet-es7-async

A sweet.js macro for ES7 async functions.
JavaScript
4
star
43

par

A go library to perform slice operations (e.g. map, filter, reduce) in parallel.
Go
4
star
44

harmony.vim

Extensive JS syntax support for VIM
Vim Script
3
star
45

Featurizr

A Modernizr extension to spice up your media queries with feature queries
JavaScript
3
star
46

Colourizr

Colourizr is a color conversion tool for web use, especially CSS
JavaScript
3
star
47

Calculatoure

A slick HTML5 calculator, able to handle a multitude of mathematical things.
JavaScript
3
star
48

inceptionscript

Write JS macros in JS
JavaScript
3
star
49

gointerfacefunc

Generate function types for go interfaces for testing
Go
3
star
50

makejs

A javascript-based build tool, similar to make.
C++
2
star
51

restzilla

A RESTful API wrapper for Bugzilla
CoffeeScript
2
star
52

rawcanvas.js

Raw pixel access with WebGL, fallback with 2DContext
JavaScript
2
star
53

script-builder

Makes it easier to manage bigger script projects.
JavaScript
2
star
54

tool-belt.js

Small JS utilities I often use
JavaScript
2
star
55

grunt-fixtures2js

Convert your fixtures into a JS object for use in tests.
JavaScript
2
star
56

paramon

paramon is a tool for parsing command line arguments. Its agenda is to make it nice to make nice command line options.
JavaScript
2
star
57

fonticon-loader

Webpack loader for icons, converting them into iconfonts.
JavaScript
2
star
58

gostringenum

Generate efficient string encodings and decodings for go enums.
Go
2
star
59

mpmc

A go library to manage communications across Multiple Producers and Multiple Consumers.
Go
2
star
60

grunt-doctor.js

A grunt task for doctor.js
CoffeeScript
1
star
61

fixtures2js

The shared library for the gulp and grunt tasks.
JavaScript
1
star
62

oocubeb

ooc port of libcubeb
ooc
1
star
63

advent-of-code-2022

Advent of Code 2022 solutions
1
star
64

Solo.js

An ES6 Promise-based task queue utility.
JavaScript
1
star
65

struct.js

Structs for JS
JavaScript
1
star
66

stupid.js

The Stupid JS Style Guide
1
star
67

orbisyn

JavaScript
1
star
68

express-riak

A Riak session store adapter for Express.
JavaScript
1
star
69

concat-vs-multiplex

A benchmark of HTTP2 push multiplexing vs concatenation/bundling.
JavaScript
1
star
70

helsinkijs-2013-10-17

My slides for my talk at HelsinkiJS 2013-10-17
CoffeeScript
1
star
71

doctor.js

Formatting agnostic documentation
JavaScript
1
star
72

privateEval.js

A javascript library to allow javascript execution in a completely safe and private scope.
JavaScript
1
star
73

chai-gulp-helpers

A simple test helper to verify that your stream returns the expected files.
JavaScript
1
star
74

watch-and-run

A simple tool for running commands when files change.
JavaScript
1
star
75

kakku-redis-store

A Redis Store for Kakku.
JavaScript
1
star
76

go-prettyformat

Stringify go values
Go
1
star
77

through2-sequence

Combine streams into a sequence where input is the first stream and output is the last.
JavaScript
1
star
78

kakku-multi-store

A multi-backend Store for Kakku.
JavaScript
1
star
79

lowlite

A syntax highlighting library for NodeJS
JavaScript
1
star
80

blog

My personal blog
JavaScript
1
star
81

kakku-lru-cache-store

An in-memory LRU cache Store for Kakku
JavaScript
1
star
82

CodeExpression.js

A javascript library to parse a multitude of languages. Use cases include syntax highlighting, minifiers, etc.
JavaScript
1
star
83

gulp-fixtures2js

A gulp plugin for fixtures2js
JavaScript
1
star
84

gulp-resolver

Replace references to source files with references to generated files.
JavaScript
1
star