Skip to content

Commit

Permalink
docs(readme): explain changing the sample rate
Browse files Browse the repository at this point in the history
This addition to the README brievly explains how the sample rate of the recording can be influenced.

fix #674
  • Loading branch information
chrisguttandin committed Mar 5, 2023
1 parent 10d09e6 commit 71358fd
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,26 @@ const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
const mediaRecorder = new MediaRecorder(stream, { mimeType: 'audio/wav' });
```

### Setting the sample rate

The `MediaRecoder` has no way to modify the sample rate directly. It uses the `sampleRate` of the given `MediaStream`. You can read the value being used like this:

```js
const { sampleRate } = stream.getAudioTracks()[0].getSettings();
```

To modifiy the sample rate of the recording you need to change the `sampleRate` of the `MediaStream`. But that's not possible either. Therefore the most reliable way is to use an `AudioContext` at the desired `sampleRate` to do the resampling.

```js
const audioContext = new AudioContext({ sampleRate: 16000 });
const mediaStreamAudioSourceNode = new MediaStreamAudioSourceNode(audioContext, { mediaStream: stream });
const mediaStreamAudioDestinationNode = new MediaStreamAudioDestinationNode(audioContext);

mediaStreamAudioSourceNode.connect(mediaStreamAudioDestinationNode);

const mediaRecorder = new MediaRecorder(mediaStreamAudioSourceNode.stream);
```

## Inner Workings

Internally two different techniques are used to enable custom encoders. In Chrome the native MediaRecorder is used to encode the stream as webm file with pcm encoded audio. Then a minimal version of [ts-ebml](https://github.com/legokichi/ts-ebml) is used to parse that pcm data to pass it on to the encoder. In other browsers the Web Audio API is used to get the pcm data of the recorded audio.

0 comments on commit 71358fd

Please sign in to comment.