• Stars
    star
    936
  • Rank 48,447 (Top 1.0 %)
  • Language
    JavaScript
  • License
    Other
  • Created almost 11 years ago
  • Updated about 1 year ago

Reviews

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

Repository Details

Audio Waveform Data Manipulation API – resample, offset and segment waveform data in JavaScript.

Build Status npm

waveform-data.js

waveform-data.js is a JavaScript library for creating zoomable representations of audio waveforms to enable visualisation of audio content.

waveform-data.js is part of a BBC R&D Browser-based audio waveform visualisation software family:

  • audiowaveform: C++ program that generates waveform data files from MP3 or WAV format audio.
  • audio_waveform-ruby: A Ruby gem that can read and write waveform data files.
  • waveform-data.js: JavaScript library that provides access to precomputed waveform data files, or can generate waveform data using the Web Audio API.
  • peaks.js: JavaScript UI component for interacting with waveforms.

We use these projects within the BBC in applications such as the BBC World Service Radio Archive and browser-based editing and sharing tools for BBC content editors.

Example of what it helps to build

Install

Use npm to install waveform-data.js, for both Node.js and browser-based applications:

npm install --save waveform-data

Usage and examples

waveform-data.js is available as a UMD module so it can be used from a <script> tag, or as a RequireJS or CommonJS module. See dist/waveform-data.js and dist/waveform-data.min.js.

Importing waveform-data.js

Using a script tag

Simply add waveform-data.js in a script tag in your HTML page:

<!DOCTYPE html>
<html>
  <body>
    <script src="/path/to/waveform-data.js"></script>
    <script>
      var waveform = new WaveformData(...);
    </script>
  </body>
</html>

Using ES6

An ES6 module build is provided for use with bundlers such as Webpack and Rollup. See dist/waveform-data.esm.js.

import WaveformData from 'waveform-data';

Using RequireJS

The UMD bundle can be used with RequireJS:

define(['WaveformData'], function(WaveformData) {
  // ...
});

Using CommonJS (Node.js)

A CommonJS build is provided for use with Node.js. See dist/waveform-data.cjs.js.

const WaveformData = require('waveform-data');

Receive binary waveform data

You can create and initialise a WaveformData object from waveform data in either binary or JSON format, using the Fetch API, as follows.

Binary format

Use audiowaveform to generate binary format waveform data, using a command such as:

audiowaveform -i track.mp3 -o track.dat -b 8 -z 256

Copy the waveform data file track.dat to your web server, then use the following code in your web application to request the waveform data:

fetch('https://example.com/waveforms/track.dat')
  .then(response => response.arrayBuffer())
  .then(buffer => WaveformData.create(buffer))
  .then(waveform => {
    console.log(`Waveform has ${waveform.channels} channels`);
    console.log(`Waveform has length ${waveform.length} points`);
  });

JSON format

Alternatively, audiowaveform can generate waveform data in JSON format:

audiowaveform -i track.mp3 -o track.json -b 8 -z 256

Use the following code to request the waveform data:

fetch('https://example.com/waveforms/track.json')
  .then(response => response.json())
  .then(json => WaveformData.create(json))
  .then(waveform => {
    console.log(`Waveform has ${waveform.channels} channels`);
    console.log(`Waveform has length ${waveform.length} points`);
  });

Using the Web Audio API

You can also create waveform data from audio in the browser, using the Web Audio API.

As input, you can either use an ArrayBuffer containing the original encoded audio (e.g., in MP3, Ogg Vorbis, or WAV format), or an AudioBuffer containing the decoded audio samples.

Note that this approach is generally less efficient than pre-processing the audio server-side, using audiowaveform.

Waveform data is created in two steps:

  • If you pass an ArrayBuffer containing encoded audio, the audio is decoded using the Web Audio API's decodeAudioData method. This must done on the browser's UI thread, so will be a blocking operation.

  • The decoded audio is processed to produce the waveform data. To avoid further blocking the browser's UI thread, by default this step is done using a Web Worker, if supported by the browser. You can disable the worker and run the processing in the main thread by setting disable_worker to true in the options.

const audioContext = new AudioContext();

fetch('https://example.com/audio/track.ogg')
  .then(response => response.arrayBuffer())
  .then(buffer => {
    const options = {
      audio_context: audioContext,
      array_buffer: buffer,
      scale: 128
    };

    return new Promise((resolve, reject) => {
      WaveformData.createFromAudio(options, (err, waveform) => {
        if (err) {
          reject(err);
        }
        else {
          resolve(waveform);
        }
      });
    });
  })
  .then(waveform => {
    console.log(`Waveform has ${waveform.channels} channels`);
    console.log(`Waveform has length ${waveform.length} points`);
  });

If you have an AudioBuffer containing decoded audio samples, e.g., from AudioContext.decodeAudioData then you can pass this directly to WaveformData.createFromAudio:

const audioContext = new AudioContext();

audioContext.decodeAudioData(arrayBuffer)
  .then((audioBuffer) => {
    const options = {
      audio_context: audioContext,
      audio_buffer: audioBuffer,
      scale: 128
    };

    return new Promise((resolve, reject) => {
      WaveformData.createFromAudio(options, (err, waveform) => {
        if (err) {
          reject(err);
        }
        else {
          resolve(waveform);
        }
      });
    });
  })
  .then(waveform => {
    console.log(`Waveform has ${waveform.channels} channels`);
    console.log(`Waveform has length ${waveform.length} points`);
  });

Drawing a waveform image

Once you've created a WaveformData object, you can use it to draw a waveform image, using the Canvas API or a visualization library such as D3.js.

Canvas example

const waveform = WaveformData.create(raw_data);

const scaleY = (amplitude, height) => {
  const range = 256;
  const offset = 128;

  return height - ((amplitude + offset) * height) / range;
}

const ctx = canvas.getContext('2d');
ctx.beginPath();

const channel = waveform.channel(0);

// Loop forwards, drawing the upper half of the waveform
for (let x = 0; x < waveform.length; x++) {
  const val = channel.max_sample(x);

  ctx.lineTo(x + 0.5, scaleY(val, canvas.height) + 0.5);
}

// Loop backwards, drawing the lower half of the waveform
for (let x = waveform.length - 1; x >= 0; x--) {
  const val = channel.min_sample(x);

  ctx.lineTo(x + 0.5, scaleY(val, canvas.height) + 0.5);
}

ctx.closePath();
ctx.stroke();
ctx.fill();

D3.js example

See demo/d3.html.

HTML

<div id="waveform-container"></div>

JavaScript

const waveform = WaveformData.create(raw_data);
const channel = waveform.channel(0);
const container = d3.select('#waveform-container');
const x = d3.scaleLinear();
const y = d3.scaleLinear();
const offsetX = 100;

const min = channel.min_array();
const max = channel.max_array();

x.domain([0, waveform.length]).rangeRound([0, 1000]);
y.domain([d3.min(min), d3.max(max)]).rangeRound([offsetX, -offsetX]);

const area = d3.svg.area()
  .x((d, i) => x(i))
  .y0((d, i) => y(min[i]))
  .y1((d, i) => y(d));

const graph = container.append('svg')
  .style('width', '1000px')
  .style('height', '200px')
  .datum(max)
  .append('path')
  .attr('transform', () => `translate(0, ${offsetX})`)
  .attr('d', area)
  .attr('stroke', 'black');

In Node.js

You can use waveform-data.js to consume or generate waveform data from a Node.js application, e.g., a web server.

const WaveformData = require('waveform-data');
const express = require('express');
const fs = require('fs');
const app = express();

app.get('/waveforms/:id.json', (req, res) => {
  res.set('Content-Type', 'application/json');

  fs.createReadStream(`path/to/${req.params.id}.json`)
    .pipe(res);
});

The following example shows a Node.js command-line application that requests waveform data from a web API and resamples it to a width of 2000 pixels.

#!/usr/bin/env node

// Save as: app/bin/cli-resampler.js

const WaveformData = require('waveform-data');
const request = require('superagent');
const args = require('yargs').argv;

request.get(`https://api.example.com/waveforms/${args.waveformid}.json`)
  .then(response => {
    const waveform = WaveformData.create(response.body);
    const resampledWaveform = waveform.resample({ width: 2000 });
    const channel = resampledWaveform.channel(0);

    process.stdout.write(JSON.stringify({
      min: channel.min_array(),
      max: channel.max_array()
    }));
});

Usage: ./app/bin/cli-resampler.js --waveformid=1337

Data format

The file format used and consumed by WaveformData is documented here as part of the audiowaveform project.

JavaScript API

Please refer here for full API documentation.

Browser support

Any browser supporting ECMAScript 5 will be enough to use the library - think Array.forEach:

  • IE9+, Firefox Stable, Chrome Stable, Safari 6+ are fully supported;
  • IE10+ is required for the TypedArray Adapter;
  • Firefox 23+ and Webkit/Blink browsers are required for Web Audio API support.

Development

To develop the code, install Node.js and npm. After obtaining the waveform-data.js source code, run npm install to install Node.js package dependencies.

Credits

This library was written by:

Thank you to all our contributors.

This program contains code adapted from Audacity, used with permission.

License

See LICENSE for details.

Contributing

Every contribution is welcomed, either it's code, idea or a merci!

Guidelines are provided and every commit is tested against unit tests using Karma runner and the Chai assertion library.

Copyright

Copyright 2021 British Broadcasting Corporation

More Repositories

1

wraith

Wraith β€” A responsive screenshot comparison tool
Ruby
4,813
star
2

Imager.js

Responsive images while we wait for srcset to finish cooking
JavaScript
3,833
star
3

peaks.js

JavaScript UI component for interacting with audio waveforms
JavaScript
2,886
star
4

audiowaveform

C++ program to generate waveform data and render waveform images from audio files
C++
1,658
star
5

sqs-consumer

Build Amazon Simple Queue Service (SQS) based applications without the boilerplate
TypeScript
1,541
star
6

bbplot

R package that helps create and export ggplot2 charts in the style used by the BBC News data team
R
1,434
star
7

VideoContext

An experimental HTML5 & WebGL video composition and rendering API.
JavaScript
1,318
star
8

simorgh

The BBC's Open Source Web Application. Contributions welcome! Used on some of our biggest websites, e.g.
JavaScript
1,283
star
9

brave

Basic Real-time AV Editor - allowing you to preview, mix, and route live audio and video streams on the cloud
Python
646
star
10

tal

TV Application Layer
JavaScript
550
star
11

react-transcript-editor

A React component to make correcting automated transcriptions of audio and video easier and faster. By BBC News Labs. - Work in progress
JavaScript
494
star
12

psammead

React component library for BBC World Service and more
JavaScript
320
star
13

newslabs-datastringer

Monitor datasets, gets alerts when something happens
JavaScript
212
star
14

html5-video-compositor

This is the BBC Research & Development UX Team's experimental shader based video composition engine for the browser. For new projects please consider using or new VideoContext library https://github.com/bbc/videocontext .
JavaScript
207
star
15

REST-API-example

Simple REST API example in Sinatra
Ruby
193
star
16

grandstand

BBC Grandstand is a collection of common CSS abstractions and utility helper classes
SCSS
190
star
17

sqs-producer

Simple scaffolding for applications that produce SQS messages
TypeScript
181
star
18

r-audio

A library of React components for building Web Audio graphs.
JavaScript
168
star
19

chaos-lambda

Randomly terminate ASG instances during business hours
Python
163
star
20

turingcodec

Source code for the Turing codec, an HEVC software encoder optimised for fast encoding of large resolution video content
C++
153
star
21

bbc-vamp-plugins

A collection of audio feature extraction algorithms written in the Vamp plugin format.
C++
152
star
22

bbc-a11y

BBC Accessibility Guidelines Checker
Gherkin
134
star
23

rcookbook

Reference manual for creating BBC-style graphics using the BBC's bbplot package built on top of R's ggplot2 library
HTML
127
star
24

gel-grid

A flexible code implementation of the GEL Grid Guidelines
SCSS
126
star
25

audio-offset-finder

Find the offset of an audio file within another audio file
Python
124
star
26

datalab-ml-training

Machine Learning Training
Jupyter Notebook
117
star
27

Similarity

Calculate similarity between documents using TF-IDF weights
Ruby
115
star
28

viewporter

In-browser responsive testing tool.
CSS
114
star
29

flashheart

A fully-featured Node.js REST client built for ease-of-use and resilience
JavaScript
114
star
30

qtff-parameter-editor

QuickTime file parameter editor for modifying transfer function, colour primary and matrix characteristics
C++
114
star
31

gel-typography

A flexible code implementation of the GEL Typography Guidelines
CSS
111
star
32

consumer-contracts

Consumer-driven contracts in JavaScript
JavaScript
105
star
33

color-contrast-checker

An accessibility checker tool for validating the color contrast based on WCAG 2.0 and WCAG 2.1 standards.
JavaScript
81
star
34

slayer

JavaScript time series spike detection for Node.js and the browser; like the Octave findpeaks function.
JavaScript
77
star
35

lrud

Left, Right, Up, Down. A spatial navigation library for devices with input via directional controls.
JavaScript
76
star
36

audio_waveform-ruby

Ruby gem that provides access to audio waveform data files generated by audiowaveform
Ruby
76
star
37

nghq

An implementation of Multicast QUIC https://tools.ietf.org/html/draft-pardue-quic-http-mcast-07
C
67
star
38

software-engineering-technical-assessments

Technical assessment for hiring
Kotlin
67
star
39

bigscreen-player

Simplified media playback for bigscreen devices
JavaScript
65
star
40

speculate

Automatically generates an RPM Spec file for your Node.js project
JavaScript
64
star
41

zeitgeist

Twitter Zeitgeist
Ruby
62
star
42

wally

Cucumber feature viewer and navigator
Ruby
57
star
43

theano-bpr

An implementation of Bayesian Personalised Ranking in Theano
Python
54
star
44

ShouldIT

A language agnostic BDD framework.
JavaScript
53
star
45

news-gem-cloudwatch-sender

Send metrics to InfluxDB from Cloudwatch
Ruby
53
star
46

unicode-bidirectional

A Javascript implementation of the Unicode 9.0.0 Bidirectional Algorithm
JavaScript
45
star
47

subtitles-generator

A node module to generate subtitles by segmenting a list of time-coded text - BBC News Labs
JavaScript
44
star
48

accessibility-news-and-you

We want to be the most accessible news website in the world. This is how.
HTML
44
star
49

codext

VS Code's editor shipped as a browser extension.
JavaScript
42
star
50

talexample

An example TV app written using TAL
JavaScript
40
star
51

rdfspace

RDFSpace constructs a vector space from any RDF dataset which can be used for computing similarities between resources in that dataset.
Python
39
star
52

digital-paper-edit-client

Work in progress - BBC News Labs digital paper edit project - React Client
JavaScript
39
star
53

clientside-recommender

A client-side recommender system implemented in Javascript.
Java
39
star
54

gel

JavaScript
39
star
55

childrens-games-starter-pack

This is the Starter Pack for Children's games, containing everything a games developer might need to start building an HTML5 game for Children's BBC. Every game should be forked into a new repository from this repo.
JavaScript
38
star
56

alephant

The Alephant framework is a collection of isolated Ruby gems, which interconnect to offer powerful message passing functionality built up around the "Broker" pattern.
Ruby
37
star
57

vc2-reference

A reference encoder and decoder for SMPTE ST 2042-1 "VC-2 Video Compression"
C++
34
star
58

ruby-lsh

Locality Sensitive Hashing in Ruby
Ruby
32
star
59

Strophejs-PubSub-Demo

A simple demo of Publish/Subscribe in the browser using Strophe.js
JavaScript
31
star
60

diarize-jruby

A simple toolkit for speaker segmentation and identification
Ruby
30
star
61

pydvbcss

Python library that implements DVB protocols for companion synchronisation
Python
28
star
62

gel-sass-tools

A collection of Sass Settings & Tools which align to key GEL values
SCSS
27
star
63

a11y-tests-web

Runs automated accessibility tests against configurable lists of webpages
JavaScript
27
star
64

RadioVisDemo

RadioDNS and RadioVIS Slideshow Protocol Demo
Python
27
star
65

device-discovery-pairing

Analysis and background research on discovery and pairing for the MediaScape project
26
star
66

lrud-spatial

Left, Right, Up, Down. A spatial navigation library for devices with input via directional controls.
JavaScript
26
star
67

node-canvas-lambda-deps

Node Canvas AWS Lambda dependencies i.e. compiled shared object files for Cairo, Pixman, libpng, libjpeg etc.
JavaScript
26
star
68

clever-thumbnailer

Audio thumbnail generator
C
25
star
69

spassky

Distributed web testing tool
JavaScript
25
star
70

bbc-speech-segmenter

A complete speech segmentation system using Kaldi and x-vectors for voice activity detection (VAD) and speaker diarisation.
Shell
24
star
71

genie

BBC Genie Games Framework
JavaScript
24
star
72

media-sequence

HTML5 media sequenced playback API: play one or multiple sequences of a same audio or video with plain JavaScript.
JavaScript
24
star
73

Chart.Bands.js

Chart.js plugin to allow banding on a chart
JavaScript
23
star
74

newslabs-Text_Analytics

A space for code and projects around analysing news content
Python
23
star
75

curriculum-data

BBC Curriculum Instance Data
23
star
76

videocontext-devtools

Chrome DevTools extension for easy VideoContext debugging.
JavaScript
22
star
77

bmx

Library and utilities to read and write broadcasting media files. Primarily supports the MXF file format
C++
22
star
78

adaptivepodcasting

A project exploring the potential of media which adapts based on sensors and data
JavaScript
21
star
79

cloudflare-queue-consumer

Build Cloudflare Queues based applications without the boilerplate (based on SQS Consumer)
TypeScript
21
star
80

UCMythTV

A full implementation of Universal Control 0.6.0 for use on a computer running Mythbuntu with a slightly modified version of MythTV (patches and configure script included).
Python
20
star
81

rdfsim

Large RDF hierarchies as vector spaces
Python
20
star
82

digital-paper-edit-electron

Work in progress - BBC News Labs digital paper edit project - Electron, Cross Platform Desktop app - Mac, Windows, Linux
C++
20
star
83

gst-ttml-subtitles

Library and elements that add support for TTML subtitles to GStreamer.
C
19
star
84

bug

Started life at BBC News - BUG enables control and monitoring of broadcast kit from a single web interface.
JavaScript
19
star
85

dvbcss-synctiming

Measuring synchronisation timing accuracy for DVB Compainion Screen Synchronisation TVs and Companions
Python
19
star
86

fcpx-xml-composer

Work in progress - Module to Convert a json sequence into an FCPX XML. For BBC News Labs digital paper edit project
JavaScript
18
star
87

bbcrd-brirs

An impulse response dataset for dynamic data-based auralisation of advanced sound systems
Common Lisp
18
star
88

MiD

Make it Digital: the BBC's Digital Creativity initiative
Arduino
17
star
89

device_api-android

DeviceAPI-Android
Ruby
17
star
90

gs-sass-tools

A collection of Sass variables, functions and mixins, part of BBC Grandstand
CSS
16
star
91

enzyme-adapter-inferno

Inferno enzyme adapter
JavaScript
16
star
92

get-title

Extract the best title value from within HTML head elements.
JavaScript
16
star
93

morty-docs

Generate a static website from markdown files
JavaScript
16
star
94

storyplayer

BBC Research & Development's Object Based Media Player
TypeScript
15
star
95

dialogger

Text-based media editing interface
JavaScript
15
star
96

bbcat-base

Base library for the BBC Audio Toolbox
C++
15
star
97

origin_simulator

A tool to simulate a (flaky) upstream origin during load and stress tests.
Elixir
15
star
98

catflap-camera

Raspberry Pi based catflap-triggered camera. As seen on TV.
Python
15
star
99

citron

Citron is an experimental quote extraction system created by BBC R&D
Python
15
star
100

crimp

Creating an md5 hash of a number, string, array, or hash in Ruby
Ruby
15
star