// Step 1: Set up the Audio Context
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
let noiseSource;
// Step 2: Create an Audio Buffer
function createDrumSound() {
const sampleRate = audioContext.sampleRate;
const bufferSize = sampleRate * 1; // 1 second buffer
const buffer = audioContext.createBuffer(1, bufferSize, sampleRate);
const data = buffer.getChannelData(0);
// Step 3: Generate Noise and Decay
for (let i = 0; i < bufferSize; i++) {
data[i] = (Math.random() * 2 - 1) * Math.exp(-i / (bufferSize / 10)); // Exponential decay
}
// Apply a lowpass filter to make it sound more like a drum
noiseSource = audioContext.createBufferSource();
noiseSource.buffer = buffer;
const filter = audioContext.createBiquadFilter();
filter.type = 'lowpass';
filter.frequency.setValueAtTime(150, audioContext.currentTime); // Lowpass filter frequency
// Create a GainNode to control the volume
const gainNode = audioContext.createGain();
gainNode.gain.setValueAtTime(10, audioContext.currentTime); // Increase the gain to make it louder
noiseSource.connect(filter);
filter.connect(gainNode);
gainNode.connect(audioContext.destination);
//gainNode.connect(audioContext.destination);
noiseSource.start();
}
// Call the function to create and play the drum sound
document.addEventListener(
'click',
() => {
createDrumSound();
}
);
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.