Created
July 29, 2021 09:15
-
-
Save jscheid/0fe0ca86dbecc7a4efb65a604284d1c1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
declare module "@alexanderolsen/libsamplerate-js" { | |
interface Options { | |
converterType: number; | |
wasmPath: string; | |
} | |
interface Module { | |
simple( | |
numSamples: number, | |
numChannels: number, | |
converterType: number, | |
inputSampleRate: number, | |
outputSampleRate: number, | |
): number; | |
} | |
export interface Src { | |
simple: (dataIn: Float32Array) => Float32Array; | |
full: (dataIn: Float32Array, dataOut: Float32Array | null) => Float32Array; | |
destroy(): void; | |
readonly sourceArray: Float32Array; | |
readonly targetArray: Float32Array; | |
readonly module: Module; | |
} | |
export const ConverterType: { | |
SRC_SINC_BEST_QUALITY: number; | |
SRC_SINC_MEDIUM_QUALITY: number; | |
SRC_SINC_FASTEST: number; | |
SRC_ZERO_ORDER_HOLD: number; | |
SRC_LINEAR: number; | |
}; | |
export const create: ( | |
nChannels: number, | |
inputSampleRate: number, | |
ouputSampleRate: number, | |
options: Options, | |
) => Promise<Src>; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { create, ConverterType, Src } from "@alexanderolsen/libsamplerate-js"; | |
import libsamplerateWasm from "@alexanderolsen/libsamplerate-js/dist/libsamplerate.wasm"; | |
export class Resampler { | |
private src: Src; | |
constructor(src: Src) { | |
this.src = src; | |
} | |
resample( | |
inputArray: Float32Array, | |
inputSampleRate: number, | |
outputSampleRate: number, | |
): Float32Array { | |
this.src.sourceArray.set(inputArray); | |
const outputFrames = this.src.module.simple( | |
inputArray.length, | |
1, // number of channels | |
ConverterType.SRC_SINC_FASTEST, | |
inputSampleRate, | |
outputSampleRate, | |
); | |
return this.src.targetArray.subarray(0, outputFrames); | |
} | |
} | |
const resamplerPromise = new Promise<Resampler>((resolve, reject) => { | |
create(1, 8000, 8000, { | |
converterType: ConverterType.SRC_SINC_FASTEST, | |
wasmPath: libsamplerateWasm, | |
}) | |
.then((src) => resolve(new Resampler(src))) | |
.catch(reject); | |
}); | |
export function loadResampler(): Promise<Resampler> { | |
return resamplerPromise; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment