Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(multichannel): Combine all audio channels #145

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
18 changes: 17 additions & 1 deletion src/recorder/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,22 @@ const SafeAudioContext: typeof AudioContext = (window as any).AudioContext || (w
const createGain = (ctx: AudioContext) => (ctx.createGain || (ctx as any).createGainNode).call(ctx);
const createScriptProcessor = (ctx: AudioContext) =>
(ctx.createScriptProcessor || (ctx as any).createJavaScriptNode).call(ctx, 4096, 1, 1);
const clamp = (min: number, max: number) => (value: number): number => Math.min(Math.max(value, min), max);

const mergeAudioChannels = (buffer: AudioBuffer): Float32Array => {
const channels = new Array(buffer.numberOfChannels).fill(null).map((_, i) => buffer.getChannelData(i));
const mergedChannelData: number[] = [];

for (let index = 0; index < channels[0].length; index++) {
const mergedSample = channels.reduce(
(result, channel) => clamp(-2_147_483_648, 2_147_483_647)(result + channel[index]),
0
);
mergedChannelData.push(mergedSample);
}

return new Float32Array(mergedChannelData);
};

export class Mp3MediaRecorder extends EventTarget {
stream: MediaStream;
Expand Down Expand Up @@ -58,7 +74,7 @@ export class Mp3MediaRecorder extends EventTarget {
throw this.getStateError('start');
}
this.processorNode.onaudioprocess = (event) => {
this.worker.postMessage(dataAvailableMessage(event.inputBuffer.getChannelData(0)));
this.worker.postMessage(dataAvailableMessage(mergeAudioChannels(event.inputBuffer)));
};
this.processorNode.connect(this.audioContext.destination);
if (this.audioContext.state === 'closed') {
Expand Down
2 changes: 1 addition & 1 deletion src/types/post-message.type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export const workerRecordingMessage = () => ({
type: PostMessageType.WORKER_RECORDING as PostMessageType.WORKER_RECORDING,
});

export const dataAvailableMessage = (data: ArrayLike<number>) => ({
export const dataAvailableMessage = (data: Float32Array) => ({
type: PostMessageType.DATA_AVAILABLE as PostMessageType.DATA_AVAILABLE,
data,
});
Expand Down