• Stars
    star
    580
  • Rank 77,010 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 7 years ago
  • Updated 6 months ago

Reviews

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

Repository Details

MediaRecorder polyfill to record audio in Edge and Safari

Audio Recorder Polyfill

MediaRecorder polyfill to record audio in Edge and Safari. Try it in online demo and see API.

  • Spec compatible. In the future when all browsers will support MediaRecorder, you will remove polyfill.
  • Small. 1.11 KB (minified and gzipped). No dependencies. It uses Size Limit to control size.
  • One file. In contrast to other recorders, this polyfill uses “inline worker” and don’t need a separated file for Web Worker.
  • MP3 and WAV encoder support.
navigator.mediaDevices.getUserMedia({ audio: true }).then(stream => {
  recorder = new MediaRecorder(stream)
  recorder.addEventListener('dataavailable', e => {
    audio.src = URL.createObjectURL(e.data)
  })
  recorder.start()
})
Sponsored by Evil Martians

Install

Install package:

npm install --save audio-recorder-polyfill

We recommend creating separated webpack/Parcel bundle with polyfill. In this case, polyfill will be downloaded only by Edge and Safari. Good browsers will download less.

Files recorded without the polyfill will not be playable on Safari, it is highly recommended to convert it to MP3 on the back-end of your application. If that’s not an option you can use the polyfill in all browsers to force the audio to be converted to the right format with the price of client’s performance.

  entry: {
    app: './src/app.js',
+   polyfill: './src/polyfill.js'
  }

Install polyfill as MediaRecorder in this new bundle src/polyfill.js:

import AudioRecorder from 'audio-recorder-polyfill'
window.MediaRecorder = AudioRecorder

Add this code to your HTML to load this new bundle only for browsers without MediaRecorder support:

+   <script>
+     if (!window.MediaRecorder) {
+       document.write(
+         decodeURI('%3Cscript defer src="/polyfill.js">%3C/script>')
+       )
+     }
+   </script>
    <script src="/app.js" defer></script>

ES Modules

Polyfill supports ES modules. You do not need to do anything for bundlers.

For quick hacks you can load polyfill from CDN. Do not use it in production because of low performance.

import AudioRecorder from 'https://cdn.jsdelivr.net/npm/audio-recorder-polyfill/index.js'
window.MediaRecorder = AudioRecorder

Usage

In the beginning, we need to show a warning in browsers without Web Audio API:

if (MediaRecorder.notSupported) {
  noSupport.style.display = 'block'
  dictaphone.style.display = 'none'
}

Then you can use standard MediaRecorder API:

let recorder

recordButton.addEventListener('click', () => {
  // Request permissions to record audio
  navigator.mediaDevices.getUserMedia({ audio: true }).then(stream => {
    recorder = new MediaRecorder(stream)

    // Set record to <audio> when recording will be finished
    recorder.addEventListener('dataavailable', e => {
      audio.src = URL.createObjectURL(e.data)
    })

    // Start recording
    recorder.start()
  })
})

stopButton.addEventListener('click', () => {
  // Stop recording
  recorder.stop()
  // Remove “recording” icon from browser tab
  recorder.stream.getTracks().forEach(i => i.stop())
})

If you need to upload record to the server, we recommend using timeslice. MediaRecorder will send recorded data every specified millisecond. So you will start uploading before recording would finish.

// Will be executed every second with next part of audio file
recorder.addEventListener('dataavailable', e => {
  sendNextPiece(e.data)
})
// Dump audio data every second
recorder.start(1000)

Audio Formats

Chrome records natively only to .webm files. Firefox to .ogg.

You can get used file format in e.data.type:

recorder.addEventListener('dataavailable', e => {
  e.data.type //=> 'audio/wav' with polyfill
              //   'audio/webm' in Chrome
              //   'audio/ogg' in Firefox
})

WAV

As default, this polyfill saves records to .wav files. Compression is not very good, but encoding is fast and simple.

MP3

For better compression you may use the MP3 encoder.

import AudioRecorder from 'audio-recorder-polyfill'
import mpegEncoder from 'audio-recorder-polyfill/mpeg-encoder'

AudioRecorder.encoder = mpegEncoder
AudioRecorder.prototype.mimeType = 'audio/mpeg'
window.MediaRecorder = AudioRecorder

Limitations

This polyfill tries to be MediaRecorder API compatible. But it still has small differences.

  • WAV format contains duration in the file header. As result, with timeslice or requestData() call, dataavailable will receive a separated file with header on every call. In contrast, MediaRecorder sends header only to first dataavailable. Other events receive addition bytes to the same file.
  • Constructor options are not supported.
  • BlobEvent.timecode is not supported.

Custom Encoder

If you need audio format with better compression, you can change polyfill’s encoder:

  import AudioRecorder from 'audio-recorder-polyfill'
+ import customEncoder from './ogg-opus-encoder'
+
+ AudioRecorder.encoder = customEncoder
+ AudioRecorder.prototype.mimeType = 'audio/ogg'
  window.MediaRecorder = AudioRecorder

The encoder should be a function with Web Worker in the body. Polyfill converts function to the string to make Web Worker.

module.exports = () => {
  function init (sampleRate) {
    
  }

  function encode (input) {
    
  }

  function dump (sampleRate) {
    
    postMessage(output)
  }

  onmessage = e => {
    if (e.data[0] === 'init') {
      init(e.data[1])
    } else if (e.data[0] === 'encode') {
      encode(e.data[1])
    } else if (e.data[0] === 'dump') {
      dump(e.data[1])
    }
  }
}

More Repositories

1

nanoid

A tiny (124 bytes), secure, URL-friendly, unique string ID generator for JavaScript
JavaScript
24,064
star
2

easings.net

Easing Functions Cheat Sheet
CSS
7,908
star
3

size-limit

Calculate the real cost to run your JS app or lib to keep good performance. Show error in pull request if the cost exceeds the limit.
JavaScript
6,487
star
4

visibilityjs

Wrapper for the Page Visibility API
JavaScript
1,825
star
5

nanoevents

Simple and tiny (107 bytes) event emitter library for JavaScript
TypeScript
1,442
star
6

autoprefixer-rails

Autoprefixer for Ruby and Ruby on Rails
Ruby
1,213
star
7

nanocolors

Use picocolors instead. It is 3 times smaller and 50% faster.
JavaScript
868
star
8

keyux

JS library to improve keyboard UI of web apps
TypeScript
380
star
9

webp-in-css

PostCSS plugin and tiny JS script (131 bytes) to use WebP in CSS background
JavaScript
346
star
10

offscreen-canvas

Polyfill for OffscreenCanvas to move Three.js/WebGL/2D canvas to Web Worker
JavaScript
332
star
11

convert-layout

JS library to convert text from one keyboard layout to other
JavaScript
251
star
12

ssdeploy

Netlify replacement to deploy simple websites with better flexibility, speed and without vendor lock-in
JavaScript
194
star
13

environment

My home config, scripts and installation process
Shell
193
star
14

nanodelay

A tiny (37 bytes) Promise wrapper around setTimeout
JavaScript
189
star
15

dual-publish

Publish JS project as dual ES modules and CommonJS package to npm
JavaScript
186
star
16

nanospy

Spy and mock methods in tests with great TypeScript support
TypeScript
138
star
17

check-dts

Unit tests for TypeScript definitions in your JS open source library
JavaScript
138
star
18

autoprefixer-core

autoprefixer-core was depreacted, use autoprefixer
JavaScript
136
star
19

transition-events

jQuery plugin to set listeners to CSS Transition animation end or specific part
JavaScript
133
star
20

evil-blocks

Tiny framework for web pages to split your app to separated blocks
JavaScript
127
star
21

rails-sass-images

Sass functions and mixins to inline images and get images size
Ruby
114
star
22

compass.js

Compass.js allow you to get compass heading in JavaScript by PhoneGap, iOS API or GPS hack.
CoffeeScript
112
star
23

evil-front

Helpers for frontend from Evil Martians
Ruby
101
star
24

rake-completion

Bash completion support for Rake
Shell
63
star
25

yaspeller-ci

Fast spelling check for Travis CI
JavaScript
61
star
26

jquery-cdn

Best way to use latest jQuery in Ruby app
Ruby
59
star
27

sitnik.ru

My homepage content and scripts
JavaScript
57
star
28

pages.js

CoffeeScript
44
star
29

fotoramajs

Fotorama for Ruby on Rails
Ruby
44
star
30

about-postcss

Keynotes about PostCSS
Ruby
29
star
31

autohide-battery

GNOME Shell extension to hide battery icon in top panel, if battery is fully charged and AC is connected.
JavaScript
28
star
32

darian

Darian Mars calendar converter
Ruby
25
star
33

better-node-test

The CLI shortcut for node --test runner with TypeScript
JavaScript
25
star
34

plain_record

Data persistence with human readable and editable storage.
Ruby
24
star
35

evolu-lang

Programming language to automatically generate programs by evolution (genetic programming).
JavaScript
22
star
36

martian-logux-demo

TypeScript
17
star
37

hide-keyboard-layout

GNOME Shell extension to hide keyboard layout indicator in status bar
JavaScript
17
star
38

twitter2vk

Script to automatically repost statuses from Twitter to VK (В Контакте)
Ruby
16
star
39

asdf-cache-action

A Github Action to install runtimes by asdf CLI with a cache
15
star
40

ci-job-number

Return CI job number to run huge tests only on first job
JavaScript
15
star
41

print-snapshots

Print Jest snapshots to check CLI output of your tool
JavaScript
15
star
42

load-resources

Load all JS/CSS files from site website
JavaScript
15
star
43

susedko

Fedora CoreOS ignition config for my home server
JavaScript
14
star
44

file-container

Store different languages in one source file
JavaScript
14
star
45

postcss-isolation

Fix global CSS with PostCSS
14
star
46

autoprefixer-cli

CLI for Autoprefixer
JavaScript
14
star
47

d2na

D²NA language for genetic programming
Ruby
11
star
48

showbox

Keynote generator
JavaScript
11
star
49

boilerplates

Boilerplate for my open source projects
JavaScript
9
star
50

postcss-way

Keynotes about PostCSS way
9
star
51

gulp-bench-summary

Display gulp-bench results in nice table view
JavaScript
8
star
52

universal-layout

Универсальная раскладка Ситника
8
star
53

anim2012

Доклад «Анимации по-новому — лень, гордыня и нетерпимость»
CSS
8
star
54

nanopurify

A tiny (from 337 bytes) HTML sanitizer
JavaScript
7
star
55

ai

6
star
56

rit3d

Доклад «Веб, теперь в 3D: Практика»
CSS
6
star
57

dis.spbstu.ru

Department homepage
Ruby
5
star
58

jstransformer-lowlight

Lowlight support for JSTransformers
JavaScript
5
star
59

jest-ci

CLI for Jest test framework, but coverage only on first CI job
JavaScript
5
star
60

evolu-steam

Evolu Steam – evolutionary computation for JavaScript
JavaScript
5
star
61

insomnis

Текст блогокниги «Инсомнис»
4
star
62

plague

Blog/book Plague engine
Ruby
4
star
63

wsd2013

Презентация «Автопрефиксер: мир без CSS-префиксов»
Ruby
4
star
64

showbox-bright

Shower Bright theme for Showbox
JavaScript
3
star
65

ruby2jar

Ruby2Jar builds JAR from a Ruby script
Ruby
3
star
66

showbox-ai

Sitnik’s theme for ShowBox
CSS
3
star
67

showbox-shower

Shower for ShowBox
JavaScript
2
star
68

on_the_islands

Ruby
2
star