It looks like you're looking to build or find a complete JavaScript-based synthesizer project with the following features:
You can take it as a base foundation, then expand with UI improvements, more waveform/filter types, or better RTTTL parsing.
html Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>RTTTL Synth + Chord + ADSR + Share + Export WAV</title>
<style>
body { font-family: sans-serif; margin: 1rem; }
label, button { margin-top: 0.5rem; display: block; }
textarea { width: 100%; height: 60px; }
input[type=range] { width: 200px; }
#log { white-space: pre-wrap; background: #eee; padding: 0.5rem; height: 150px; overflow-y: auto;}
</style>
</head>
<body>
<h2>RTTTL Synth with Chords and ADSR</h2>
<label>RTTTL String (use '+' for chords, ex: c+e+g)
<textarea id="rtttl">Imperial:d=4,o=5,b=100:c+e+g,4p,g</textarea>
</label>
<label>Loop Playback <input type="checkbox" id="loop" /></label>
<h3>ADSR Envelope</h3>
<label>Attack: <input type="range" id="attack" min="0" max="2" step="0.01" value="0.05" /> <span id="atkval">0.05</span> s</label>
<label>Decay: <input type="range" id="decay" min="0" max="2" step="0.01" value="0.1" /> <span id="decval">0.10</span> s</label>
<label>Sustain: <input type="range" id="sustain" min="0" max="1" step="0.01" value="0.6" /> <span id="susval">0.60</span></label>
<label>Release: <input type="range" id="release" min="0" max="3" step="0.01" value="0.5" /> <span id="relval">0.50</span> s</label>
<h3>Oscillator & Filter</h3>
<label>Waveform:
<select id="waveform">
<option value="sine">Sine</option>
<option value="square" selected>Square</option>
<option value="triangle">Triangle</option>
<option value="sawtooth">Sawtooth</option>
<option value="pulse">Pulse (custom)</option>
</select>
</label>
<label>Pulse Width (for Pulse wave only): <input type="range" id="pulseWidth" min="0.01" max="0.99" step="0.01" value="0.5" /> <span id="pulseval">0.50</span></label>
<label>Filter frequency: <input type="range" id="filterFreq" min="100" max="15000" value="15000" step="1" /> <span id="filtval">15000</span> Hz</label>
<button id="play">Play / Stop</button>
<button id="copy">Copy RTTTL</button>
<button id="share">Generate Share URL</button>
<button id="export">Export WAV (5s)</button>
<h3>Log / Output</h3>
<div id="log"></div>
<script>
(() => {
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
let scheduledNotes = [];
let isPlaying = false;
let startTime = 0;
let loop = false;
const noteFrequencies = {
'c': 16.35,
'c#': 17.32, 'd#': 19.45, 'f#': 23.12, 'g#': 25.96, 'a#': 29.14,
'd': 18.35, 'e': 20.60, 'f': 21.83, 'g': 24.50, 'a': 27.50, 'b': 30.87
};
// Calculate frequency of note with octave
function getFreq(note, octave){
// note is like "c", "c#", ...
let base = note.toLowerCase();
if (base.length === 1) {
base = base;
} else if (base.length === 2) {
base = base[0] + '#' ;
}
let f0 = noteFrequencies[base];
if (!f0) return null;
return f0 * Math.pow(2, octave);
}
// Parse RTTTL (simplified)
function parseRTTTL(str) {
// format: name:d=4,o=5,b=140: melody,...
const parts = str.split(':');
if(parts.length !== 3) return null;
let [name, defaults, melody] = parts;
let defMap = { d:4, o:6, b:63 };
for(let def of defaults.split(',')) {
let [k,v] = def.split('=');
if(k && v) defMap[k.trim()] = isNaN(v) ? v : Number(v);
}
// b = bpm, d= default duration, o=default octave
const bpm = defMap.b;
const defaultDur = defMap.d;
const defaultOct = defMap.o;
// melody split on commas
let notes = [];
const noteParts = melody.split(',');
for (let np of noteParts) {
np = np.trim().toLowerCase();
if (!np) continue;
/*
Each note can be:
- duration (optional) + note + octave (optional) + dot (optional): e.g. 4c#6., 8p, c#, 16g
- chords: notes joined by '+' like c+e+g
*/
const chordNotes = np.split('+');
const chord = chordNotes.map(n=>{
// parse each note in chord
let duration = defaultDur;
let octave = defaultOct;
let dotted = false;
// Extract duration at beginning if present
const durMatch = n.match(/^(\d+)/);
if(durMatch) {
duration = Number(durMatch[1]);
n = n.slice(durMatch[1].length);
}
// Extract dotted
if (n.endsWith('.')) {
dotted = true;
n = n.slice(0, -1);
}
// extract octave digit at end if present
const octMatch = n.match(/(\d)$/);
if(octMatch) {
octave = Number(octMatch[1]);
n = n.slice(0, -1);
}
let noteName = n;
if(noteName === 'p') return {freq:0, duration, dotted};
// frequency:
let freq = getFreq(noteName, octave);
if(!freq) freq = 0;
if(dotted) duration = duration * 1.5;
return {freq, duration};
});
notes.push(chord);
}
return {name, bpm, notes};
}
// Convert duration to seconds based on bpm:
function durationToSeconds(duration, bpm) {
// duration: RTTTL number, the denominator of note length
// tempo = bpm beats per minute
// duration 4 means quarter note, so length = 60/bpm * 4/duration
return (60 / bpm) * (4 / duration);
}
// Envelope: simple ADSR
function applyEnvelope(gainNode, now, duration, ADSR) {
const {attack, decay, sustain, release} = ADSR;
const attackEnd = now + attack;
const decayEnd = attackEnd + decay;
const releaseStart = now + duration;
gainNode.gain.cancelScheduledValues(now);
gainNode.gain.setValueAtTime(0, now);
gainNode.gain.linearRampToValueAtTime(1, attackEnd);
gainNode.gain.linearRampToValueAtTime(sustain, decayEnd);
gainNode.gain.setValueAtTime(sustain, releaseStart);
gainNode.gain.linearRampToValueAtTime(0, releaseStart + release);
}
// Play one note chord (array of notes)
function playChord(freqs, duration, ADSR, waveform, pulseWidth, filterFreq, startAt) {
const nodes = [];
const now = audioCtx.currentTime + startAt;
const filter = audioCtx.createBiquadFilter();
filter.type = 'lowpass';
filter.frequency.setValueAtTime(filterFreq, now);
filter.Q.value = 1;
// Create gain node for ADSR envelope
const gainNode = audioCtx.createGain();
gainNode.gain.setValueAtTime(0, now);
gainNode.connect(filter);
filter.connect(audioCtx.destination);
freqs.forEach(freq => {
if (freq === 0) return; // rest
// Osc nodes
let osc;
if(waveform === 'pulse') {
// Create custom pulse wave using PWM technique
const real = new Float32Array(2);
const imag = new Float32Array(2);
real[0] = 0; imag[0] = 0;
// First harmonic
real[1] = Math.cos(Math.PI * pulseWidth);
imag[1] = Math.sin(Math.PI * pulseWidth);
const wave = audioCtx.createPeriodicWave(real, imag);
osc = audioCtx.createOscillator();
osc.setPeriodicWave(wave);
} else {
osc = audioCtx.createOscillator();
osc.type = waveform;
}
osc.frequency.setValueAtTime(freq, now);
osc.connect(gainNode);
osc.start(now);
osc.stop(now + duration + ADSR.release + 0.1); // Small overrun to release tail
nodes.push(osc);
});
applyEnvelope(gainNode, now, duration, ADSR);
scheduledNotes.push({stopAt: now + duration + ADSR.release + 0.1, nodes, gainNode, filter});
}
// Stop immediately
function stopPlaying() {
scheduledNotes.forEach(({nodes, gainNode, filter}) => {
nodes.forEach(osc => osc.stop());
gainNode.disconnect();
filter.disconnect();
});
scheduledNotes = [];
isPlaying = false;
}
// Play entire RTTTL melody (chords, loop optional)
async function playMelody(data, ADSR, waveform, pulseWidth, filterFreq, loopFlag) {
if(api.sequencer) {
// A sequencer is running: stop first
stopPlaying();
clearTimeout(api.sequencer);
api.sequencer = null;
}
isPlaying = true;
loop = loopFlag;
let beatLengthSec = 60 / data.bpm;
async function playSequence() {
startTime = audioCtx.currentTime;
for(let chord of data.notes) {
if(!isPlaying) break;
// chord: array of notes with freq and duration or zero freq for rest
// duration is in RTTTL units (for first note in chord, assume all same)
// RTTTL notation stores duration per note, but chords should share same duration ideally
const durations = chord.map(n => n.duration || 4);
const durationsUnique = [...new Set(durations)];
let durationVal = durationsUnique[0]; // pick first duration
// calculate seconds for duration:
let t = durationToSeconds(durationVal, data.bpm);
// get freqs
const freqs = chord.map(n => n.freq || 0);
playChord(freqs, t, ADSR, waveform, pulseWidth, filterFreq, 0);
// Wait duration
await new Promise(r => setTimeout(r, t * 1000));
if(!isPlaying) break;
}
if(loop && isPlaying) {
playSequence();
} else {
isPlaying = false;
api.sequencer = null;
}
}
playSequence();
}
// Export a 5 seconds WAV (mono) of the synth playing (simple)
// This is a naive generated sine+square wave demo for export
// For full synth, offline audioContext would be better
async function exportWav(data, ADSR, waveform, pulseWidth, filterFreq) {
const offlineCtx = new OfflineAudioContext(1, offlineSampleRate * offlineDuration, offlineSampleRate);
const bpm = data.bpm;
let startAt = 0;
const offlineGain = offlineCtx.createGain();
offlineGain.connect(offlineCtx.destination);
// play the melody in offlineCtx by scheduling oscillators etc
for(let chord of data.notes) {
const durations = chord.map(n => n.duration || 4);
const durationsUnique = [...new Set(durations)];
let durationVal = durationsUnique[0];
let t = (60 / bpm) * (4 / durationVal);
const freqs = chord.map(n => n.freq || 0);
const filter = offlineCtx.createBiquadFilter();
filter.type = 'lowpass';
filter.frequency.setValueAtTime(filterFreq, startAt);
filter.Q.value = 1;
const gainNode = offlineCtx.createGain();
gainNode.gain.setValueAtTime(0, startAt);
gainNode.connect(filter);
filter.connect(offlineGain);
freqs.forEach(freq => {
if(freq === 0) return;
let osc;
if(waveform === 'pulse') {
const real = new Float32Array(2);
const imag = new Float32Array(2);
real[0] = 0; imag[0] = 0;
real[1] = Math.cos(Math.PI * pulseWidth);
imag[1] = Math.sin(Math.PI * pulseWidth);
const wave = offlineCtx.createPeriodicWave(real, imag);
osc = offlineCtx.createOscillator();
osc.setPeriodicWave(wave);
} else {
osc = offlineCtx.createOscillator();
osc.type = waveform;
}
osc.frequency.setValueAtTime(freq, startAt);
osc.connect(gainNode);
osc.start(startAt);
osc.stop(startAt + t + ADSR.release + 0.1);
});
// Envelope:
const attackEnd = startAt + ADSR.attack;
const decayEnd = attackEnd + ADSR.decay;
const releaseStart = startAt + t;
gainNode.gain.setValueAtTime(0, startAt);
gainNode.gain.linearRampToValueAtTime(1, attackEnd);
gainNode.gain.linearRampToValueAtTime(ADSR.sustain, decayEnd);
gainNode.gain.setValueAtTime(ADSR.sustain, releaseStart);
gainNode.gain.linearRampToValueAtTime(0, releaseStart + ADSR.release);
startAt += t;
}
const rendered = await offlineCtx.startRendering();
// Convert buffer to WAV blob
const wavBuffer = bufferToWav(rendered);
const blob = new Blob([wavBuffer], {type: 'audio/wav'});
const url = URL.createObjectURL(blob);
downloadLink.href = url;
downloadLink.download = (data.name || 'export') + '.wav';
downloadLink.click();
URL.revokeObjectURL(url);
}
// buffer to WAV helper (mono 16bit)
function bufferToWav(buffer) {
let numChannels = buffer.numberOfChannels;
let sampleRate = buffer.sampleRate;
let length = buffer.length * numChannels * 2 + 44;
let bufferArray = new ArrayBuffer(length);
let view = new DataView(bufferArray);
/* RIFF identifier */
writeString(view, 0, 'RIFF');
/* file length */
view.setUint32(4, length - 8, true);
/* RIFF type */
writeString(view, 8, 'WAVE');
/* format chunk identifier */
writeString(view, 12, 'fmt ');
/* format chunk length */
view.setUint32(16, 16, true);
/* sample format (raw) */
view.setUint16(20, 1, true);
/* channel count */
view.setUint16(22, numChannels, true);
/* sample rate */
view.setUint32(24, sampleRate, true);
/* byte rate (sample rate * block align) */
view.setUint32(28, sampleRate * numChannels * 2, true);
/* block align (channel count * bytes per sample) */
view.setUint16(32, numChannels * 2, true);
/* bits per sample */
view.setUint16(34, 16, true);
/* data chunk identifier */
writeString(view, 36, 'data');
/* data chunk length */
view.setUint32(40, length - 44, true);
// Write interleaved data
let offset = 44;
for(let i = 0; i < buffer.length; i++) {
for(let ch = 0; ch < numChannels; ch++) {
let sample = buffer.getChannelData(ch)[i];
sample = Math.max(-1, Math.min(1, sample));
view.setInt16(offset, sample < 0 ? sample * 0x8000 : sample * 0x7FFF, true);
offset += 2;
}
}
return bufferArray;
}
function writeString(view, offset, str) {
for(let i = 0; i < str.length; i++) {
view.setUint8(offset + i, str.charCodeAt(i));
}
}
// Helpers & Bindings
const rtttlEl = document.getElementById('rtttl');
const loopEl = document.getElementById('loop');
const playBtn = document.getElementById('play');
const copyBtn = document.getElementById('copy');
const shareBtn = document.getElementById('share');
const exportBtn = document.getElementById('export');
const logEl = document.getElementById('log');
const attackEl = document.getElementById('attack');
const decayEl = document.getElementById('decay');
const sustainEl = document.getElementById('sustain');
const releaseEl = document.getElementById('release');
const atkVal = document.getElementById('atkval');
const decVal = document.getElementById('decval');
const susVal = document.getElementById('susval');
const relVal = document.getElementById('relval');
const waveformEl = document.getElementById('waveform');
const pulseWidthEl = document.getElementById('pulseWidth');
const pulseVal = document.getElementById('pulseval');
const filterFreqEl = document.getElementById('filterFreq');
const filtVal = document.getElementById('filtval');
const downloadLink = document.createElement('a');
downloadLink.style.display = 'none';
document.body.appendChild(downloadLink);
// Update ADSR display values:
function updateADSRDisplay() {
atkVal.textContent = attackEl.value;
decVal.textContent = decayEl.value;
susVal.textContent = sustainEl.value;
relVal.textContent = releaseEl.value;
}
attackEl.addEventListener('input', () => { updateADSRDisplay(); });
decayEl.addEventListener('input', () => { updateADSRDisplay(); });
sustainEl.addEventListener('input', () => { updateADSRDisplay(); });
releaseEl.addEventListener('input', () => { updateADSRDisplay(); });
pulseWidthEl.addEventListener('input', () => {
pulseVal.textContent = pulseWidthEl.value;
});
filterFreqEl.addEventListener('input', () => {
filtVal.textContent = filterFreqEl.value;
});
updateADSRDisplay();
// Play/Stop Handler
playBtn.addEventListener('click', () => {
if(isPlaying) {
stopPlaying();
playBtn.textContent = "Play / Stop";
log("Stopped");
} else {
const data = parseRTTTL(rtttlEl.value);
if(!data) {
alert('Failed to parse RTTTL string');
return;
}
const ADSR = {
attack: parseFloat(attackEl.value),
decay: parseFloat(decayEl.value),
sustain: parseFloat(sustainEl.value),
release: parseFloat(releaseEl.value)
};
const waveform = waveformEl.value;
const pulseWidth = parseFloat(pulseWidthEl.value);
const filterFreq = parseFloat(filterFreqEl.value);
const loopFlag = loopEl.checked;
// Resume AudioContext if suspended due to browser policies
if(audioCtx.state === 'suspended') {
audioCtx.resume();
}
playMelody(data, ADSR, waveform, pulseWidth, filterFreq, loopFlag);
playBtn.textContent = "Stop";
log("Playing: " + data.name);
}
});
// Copy RTTTL to clipboard
copyBtn.addEventListener('click', () => {
navigator.clipboard.writeText(rtttlEl.value).then(() => {
log("Copied RTTTL to clipboard");
}).catch(console.error);
});
// Share URL with #hash to encode RTTTL + settings
shareBtn.addEventListener('click', () => {
const params = {
r: encodeURIComponent(rtttlEl.value),
a: attackEl.value,
d: decayEl.value,
s: sustainEl.value,
rls: releaseEl.value,
w: waveformEl.value,
p: pulseWidthEl.value,
f: filterFreqEl.value,
l: loopEl.checked ? "1" : "0"
};
const hash = Object.entries(params).map(([k,v])=>`${k}=${v}`).join('&');
const url = location.origin + location.pathname + '#/' + hash;
prompt("Share this URL:", url);
});
// On page load, parse hash and apply parameters
function parseHash() {
if(location.hash.startsWith('#/')) {
const hashStr = location.hash.slice(2);
const parts = new URLSearchParams(hashStr);
const r = parts.get('r');
if(r) rtttlEl.value = decodeURIComponent(r);
const a = parts.get('a'); if(a) attackEl.value = a;
const d = parts.get('d'); if(d) decayEl.value = d;
const s = parts.get('s'); if(s) sustainEl.value = s;
const rls = parts.get('rls'); if(rls) releaseEl.value = rls;
const w = parts.get('w'); if(w) waveformEl.value = w;
const p = parts.get('p'); if(p) pulseWidthEl.value = p;
const f = parts.get('f'); if(f) filterFreqEl.value = f;
const l = parts.get('l'); loopEl.checked = (l === "1");
updateADSRDisplay();
pulseVal.textContent = pulseWidthEl.value;
filtVal.textContent = filterFreqEl.value;
log("Loaded settings from URL hash");
}
}
parseHash();
// Export Button triggers offline rendering & save WAV (5 seconds max)
const offlineSampleRate = 44100;
const offlineDuration = 5;
exportBtn.addEventListener('click', () => {
const data = parseRTTTL(rtttlEl.value);
if(!data) {
alert('Failed to parse RTTTL string');
return;
}
const ADSR = {
attack: parseFloat(attackEl.value),
decay: parseFloat(decayEl.value),
sustain: parseFloat(sustainEl.value),
release: parseFloat(releaseEl.value)
};
const waveform = waveformEl.value;
const pulseWidth = parseFloat(pulseWidthEl.value);
const filterFreq = parseFloat(filterFreqEl.value);
exportBtn.disabled = true;
exportBtn.textContent = 'Exporting... Please wait';
setTimeout(() => {
exportWav(data, ADSR, waveform, pulseWidth, filterFreq).then(() => {
exportBtn.disabled = false;
exportBtn.textContent = 'Export WAV (5s)';
log("Export complete");
}).catch(e => {
alert('Export failed: ' + e);
exportBtn.disabled = false;
exportBtn.textContent = 'Export WAV (5s)';
});
}, 100);
});
function log(msg) {
logEl.textContent = msg + '\n' + logEl.textContent;
}
// Expose API for stop sound on unload
window.addEventListener('beforeunload', () => stopPlaying());
// Simple api object
window.api = {};
})();
</script>
</body>
</html>
If you want me to help further with any aspect (e.g. improving the parser, adding MIDI support, advanced waveforms) just ask!