functions for generating .wav file data 🔉
generate a three-second wav file of a 440hz sine wave at 48000 samples per second
import { getWavBuffer } from "clumsy-wav";
const lengthOfAudioInSeconds = 3;
const sampleRate: SampleRate = 48000;
const sampleCount = lengthOfAudioInSeconds * sampleRate;
const channelsData: MonoChannelsData = [
new Array(sampleCount).fill(undefined).map((_, sampleIndex) => {
const waveFrequency = 440;
const frequencySampleRateScalar = sampleCount / sampleRate;
const angleStep = (2 * Math.PI) / sampleRate;
const sampleAngle = sampleIndex * angleStep;
return Math.sin(waveFrequency * frequencySampleRateScalar * sampleAngle);
}),
];
const wavBuffer = getWavBuffer(sampleRate, channelsData);
// within some async onClick handler
const audioContext = new AudioContext({
sampleRate,
});
const audioSourceNode = new AudioBufferSourceNode(currentAudioContext);
audioSourceNode.buffer = await audioContext.decodeAudioData(wavBuffer.slice(0));
audioSourceNode.connect(audioContext.destination);
audioSourceNode.start();
// within some onClick handler
const wavFile = new Blob([wavBuffer], {
type: "audio/wav",
});
const wavUrl = URL.createObjectURL(wavFile);
const tempAnchor = document.createElement("a");
tempAnchor.href = wavUrl;
tempAnchor.download = "sine440.wav";
tempAnchor.click();
URL.revokeObjectURL(wavUrl);
yarn add clumsy-wav