It sounds like you're looking for a web-based synthesizer project with these features:
- HTML interface
- RTTTL (Ring Tone Text Transfer Language) parser to load melodies
- Support for chords (with "+" notation)
- Loop playback
- Copy/share/export functionality
- Custom ADSR envelope
- Oscillator(s) with pulse width control
- Filter with modulation (LFO)
- Effects like flanger
- Ability to export audio (WAV)
- Possibly hash-based state saving (
#/ in URL)
Below is a starter JavaScript + HTML project outline that integrates or can integrate all these features using the Web Audio API and basic UI.
Features we'll cover in the example snippet:
- RTTTL parser
- Playback of notes including chords (+)
- Looping playback
- ADSR envelope
- Oscillator with pulse width modulation
- LFO for filter cutoff
- Filter and flanger effect
- WAV export
- Hash-based sharing
- Copy to clipboard
Basic working example (expandable)
Here is a minimal but integrated example for you to build on:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>RTTTL Synth with ADSR, filter, LFO, flanger, WAV export</title>
<style>
body { font-family: sans-serif; max-width: 600px; margin: 2em auto; }
textarea { width: 100%; height: 4em; font-family: monospace; }
input, button { margin-top: 0.5em; }
label { display: block; margin-top: 1em; }
small { color: #555; }
</style>
</head>
<body>
<h1>RTTTL Synth</h1>
<label>
RTTTL String:
<textarea id="rtttl-input" spellcheck="false">Enter RTTTL here (e.g. Entertainer:d=4,o=5,b=140:8d,8d+,8d+,8d)</textarea>
</label>
<label>
Loop playback:
<input type="checkbox" id="loop" />
</label>
<label>
ADSR Envelope:
<br/>A (attack seconds): <input type="number" id="attack" step="0.01" value="0.05" min="0" max="1" />
<br/>D (decay seconds): <input type="number" id="decay" step="0.01" value="0.1" min="0" max="1" />
<br/>S (sustain 0-1): <input type="number" id="sustain" step="0.01" value="0.6" min="0" max="1" />
<br/>R (release seconds): <input type="number" id="release" step="0.01" value="0.2" min="0" max="1" />
</label>
<label>
Pulse Width (%): <input type="range" id="pulseWidth" min="0" max="100" value="50" />
</label>
<label>
Filter Cutoff (Hz): <input type="range" id="filterCutoff" min="100" max="5000" value="1000" />
</label>
<label>
LFO Rate (Hz):
<input type="number" id="lfoRate" value="3" min="0.1" max="20" step="0.1" />
</label>
<label>
Flanger Depth (ms):
<input type="number" id="flangerDepth" value="5" min="0" max="20" step="0.1" />
</label>
<div>
<button id="play">Play</button>
<button id="stop">Stop</button>
<button id="exportWav">Export WAV</button>
<button id="copy">Copy RTTTL</button>
</div>
<div id="status"></div>
<script>
(() => {
// Globals
const AudioContext = window.AudioContext || window.webkitAudioContext;
let audioCtx = null;
let isPlaying = false;
let scheduledNotes = [];
let playbackStartTime;
let loop = false;
// UI elements
const rtttlInput = document.getElementById('rtttl-input');
const loopCheckbox = document.getElementById('loop');
const attackInput = document.getElementById('attack');
const decayInput = document.getElementById('decay');
const sustainInput = document.getElementById('sustain');
const releaseInput = document.getElementById('release');
const pulseWidthInput = document.getElementById('pulseWidth');
const filterCutoffInput = document.getElementById('filterCutoff');
const lfoRateInput = document.getElementById('lfoRate');
const flangerDepthInput = document.getElementById('flangerDepth');
const playBtn = document.getElementById('play');
const stopBtn = document.getElementById('stop');
const exportBtn = document.getElementById('exportWav');
const copyBtn = document.getElementById('copy');
const statusDiv = document.getElementById('status');
// --- RTTTL parser ---
// Parses RTTTL and returns array of {freq, duration (sec)}
function parseRTTTL(rtttl) {
// Simple RTTTL parser supporting chords via "+"
// RTTTL format: name:d=4,o=5,b=140:8d,8d+,8d+
// Note: This is a basic parser, can be improved
let [namePart, defaultsPart, melodyPart] = rtttl.split(':');
if (!melodyPart) throw new Error('Invalid RTTTL format');
// Default parsing
const defaults = {d:4, o:6, b:63}; // defaults per spec
defaultsPart.split(',').forEach(def => {
let [k,v] = def.split('=');
if (k && v) defaults[k.trim()] = v.trim();
});
// calculate tick (duration of a quarter note in seconds)
const bpm = parseInt(defaults.b);
const beatDuration = 60 / bpm; // duration of quarter note in seconds
// Notes frequency map: note name + octave => freqHz
const noteFreq = {};
const A4 = 440;
const notes = ['c','c#','d','d#','e','f','f#','g','g#','a','a#','b'];
// Pre-fill noteFreq for octave 0 to 8
for (let octave=0; octave<=8; octave++) {
for(let i=0; i<notes.length; i++){
// MIDI note number for C-1 is 0, but here octave 4 is middle
// Calculate frequency:
let noteNumber = (octave*12) + i;
// MIDI note for A4 = 69
let freq = A4 * Math.pow(2, (noteNumber - 57) / 12);
noteFreq[notes[i]+octave] = freq;
}
}
// Parse melody
const tokens = melodyPart.split(',');
const events = [];
for (const tokenRaw of tokens){
// Token can be chord
// Examples:
// 8d -> eighth note D
// 8d+16f -> chord D + F with 8th and 16th note length? We'll treat all as same duration
const token = tokenRaw.trim();
if(!token) continue;
// Split chord notes by "+"
const chordNotes = token.split('+');
let duration = null;
let octave = parseInt(defaults.o);
let noteStrs = [];
for (const chordNoteRaw of chordNotes){
// Parse duration, note, octave in each
const noteMatch = chordNoteRaw.match(/^(\d+)?([a-gp]#?)(\d+)?(\.*)$/i);
if (!noteMatch) {
statusDiv.textContent = `Failed to parse note: ${chordNoteRaw}`;
continue;
}
let [, durStr, note, octStr, dots] = noteMatch;
if(durStr) duration = parseInt(durStr); else duration = defaults.d; // use first duration
if(octStr) octave = parseInt(octStr);
noteStrs.push({note: note.toLowerCase(), octave});
}
// Calculate duration in seconds with dotted notes
// Duration is 1/duration * whole note length (4 beats)
let baseDuration = (4 / duration) * beatDuration;
// Account for dots (length increased by 1/2, 1/4 etc)
// For simplicity, just single dot increases 1.5x
// (Optional: parse dots from note suffix)
// We'll assume no dots for chords for simplicity
events.push({notes: noteStrs, duration: baseDuration});
}
return events;
}
// --- Audio Parts ---
// Create pulse wave with variable pulse width - using periodicWave
// Pulse width from 0 to 1, default 0.5
function createPulseWave(pulseWidth=0.5){
// Fourier series with odd harmonics and amplitudes depending on pulse width
const real = new Float32Array(16);
const imag = new Float32Array(16);
for(let n=1; n<16; n+=2){
real[n] = 4 / (n * Math.PI) * Math.sin(n * Math.PI * pulseWidth);
imag[n] = 0;
}
const wave = audioCtx.createPeriodicWave(real, imag);
return wave;
}
// ADSR envelope gain ramp
function applyADSR(gainNode, startTime, duration, attack, decay, sustain, release) {
const attackEnd = startTime + attack;
const decayEnd = attackEnd + decay;
const releaseStart = startTime + duration;
gainNode.gain.setValueAtTime(0, startTime);
gainNode.gain.linearRampToValueAtTime(1, attackEnd);
gainNode.gain.linearRampToValueAtTime(sustain, decayEnd);
// hold sustain
gainNode.gain.setValueAtTime(sustain, releaseStart);
gainNode.gain.linearRampToValueAtTime(0, releaseStart + release);
}
// Play a single note or chord at given time and duration
// notes: array of {note:'c', octave:5} objects
// duration: seconds
// returns array of oscillator source nodes for stop controls
function playNote(notes, time, duration) {
let sources = [];
// Create gain node for this chord ADSR
const gainNode = audioCtx.createGain();
gainNode.gain.setValueAtTime(0, time);
gainNode.connect(masterGain);
// Envelope params
const attack = parseFloat(attackInput.value);
const decay = parseFloat(decayInput.value);
const sustain = parseFloat(sustainInput.value);
const release = parseFloat(releaseInput.value);
applyADSR(gainNode, time, duration, attack, decay, sustain, release);
for(const n of notes){
let freq = 0;
if(n.note === 'p') {
// pause
freq = 0;
} else {
let key = n.note + n.octave;
freq = frequencyMap[key] || 0;
}
if(freq <= 0) continue; // skip rests
let osc = audioCtx.createOscillator();
// Pulse wave with pulseWidth
// Web Audio API oscillator supports 'square' but no direct pulse width
// So create custom Pulse wave periodic wave
const pw = pulseWidthInput.value / 100;
const wave = createPulseWave(pw);
osc.setPeriodicWave(wave);
osc.frequency.setValueAtTime(freq, time);
// Connect oscillator to gainNode (which connects to filter chain)
osc.connect(gainNode);
osc.start(time);
osc.stop(time + duration + release + 0.1);
sources.push(osc);
}
return sources;
}
// Parse RTTTL string and precompute array of notes with duration (seconds)
let events = [];
let frequencyMap = {};
// Initialize frequencyMap for notes c0..b8
(function initFrequencyMap(){
const A4 = 440;
const notes = ['c','c#','d','d#','e','f','f#','g','g#','a','a#','b'];
for (let octave=0; octave<=8; octave++) {
for(let i=0; i<notes.length; i++){
let noteNumber = (octave*12) + i;
let freq = A4 * Math.pow(2, (noteNumber - 57) / 12);
frequencyMap[notes[i]+octave] = freq;
}
}
})();
// --- Synth Chain ---
let masterGain;
let filter;
let flangerDelay;
let flangerOsc;
let flangerGain;
function createSynth(){
audioCtx = new AudioContext();
masterGain = audioCtx.createGain();
masterGain.gain.value = 0.2;
// filter with cutoff freq controlled by slider and LFO
filter = audioCtx.createBiquadFilter();
filter.type = "lowpass";
filter.frequency.value = parseFloat(filterCutoffInput.value);
// LFO for filter frequency modulation
flangerDelay = audioCtx.createDelay();
flangerGain = audioCtx.createGain();
flangerOsc = audioCtx.createOscillator();
// Modulation of delayTime for flanger
flangerOsc.type = 'sine';
flangerOsc.frequency.value = 0.5;
flangerGain.gain.value = 0.005; // 5 ms approx
flangerOsc.connect(flangerGain);
flangerGain.connect(flangerDelay.delayTime);
flangerDelay.delayTime.value = 0.005;
// Chain
masterGain.connect(filter);
filter.connect(flangerDelay);
flangerDelay.connect(audioCtx.destination);
flangerOsc.start();
// LFO for filter cutoff frequency
let lfo = audioCtx.createOscillator();
lfo.type = "sine";
lfo.frequency.value = parseFloat(lfoRateInput.value);
let lfoGain = audioCtx.createGain();
lfoGain.gain.value = 500; // modulation range +/- 500 Hz
lfo.connect(lfoGain);
lfoGain.connect(filter.frequency);
lfo.start();
return {
lfo,
lfoGain,
flangerOsc,
flangerGain,
masterGain,
filter,
flangerDelay
};
}
let synth;
function onParameterChange(){
if(!synth) return;
synth.filter.frequency.value = parseFloat(filterCutoffInput.value);
synth.lfo.frequency.value = parseFloat(lfoRateInput.value);
synth.flangerGain.gain.value = parseFloat(flangerDepthInput.value) / 1000; // Convert ms to s
// pulseWidth update happens per oscillators on play
}
// --- Playback ---
// Schedule all notes with WebAudio
function scheduleNotes() {
if(isPlaying) return;
if(!audioCtx) synth = createSynth();
try {
events = parseRTTTL(rtttlInput.value);
} catch(e) {
statusDiv.textContent = 'Parse error: ' + e.message;
return;
}
if(events.length === 0) {
statusDiv.textContent = "No notes to play.";
return;
}
schedulePlayback();
}
function schedulePlayback(){
loop = loopCheckbox.checked;
isPlaying = true;
playbackStartTime = audioCtx.currentTime + 0.1; // small delay
let currentTime = playbackStartTime;
scheduledNotes.length = 0;
events.forEach(ev => {
let sources = playNote(ev.notes, currentTime, ev.duration);
scheduledNotes.push(...sources);
currentTime += ev.duration;
});
if(loop){
// Schedule loop restart
loopTimer = setTimeout(() => {
if(isPlaying){
schedulePlayback();
}
}, (currentTime - playbackStartTime)*1000);
}
}
// Stop playback
function stopPlayback(){
if(!isPlaying) return;
scheduledNotes.forEach(osc => {
try {
osc.stop();
} catch(e){}
});
scheduledNotes = [];
if (loopTimer) clearTimeout(loopTimer);
isPlaying = false;
if(audioCtx) audioCtx.close();
audioCtx = null;
statusDiv.textContent = "Stopped.";
}
// Copy RTTTL text to clipboard
function copyRTTTL(){
navigator.clipboard.writeText(rtttlInput.value).then(() => {
statusDiv.textContent = "RTTTL copied to clipboard!";
});
}
// Export WAV
async function exportWav() {
try {
statusDiv.textContent = "Rendering WAV...";
if(!audioCtx) synth = createSynth();
// Create OfflineAudioContext for rendering wav buffer
const sampleRate = 44100;
const length = Math.ceil(events.reduce((acc,e)=> acc+e.duration,0)*sampleRate) + sampleRate;
const offlineCtx = new OfflineAudioContext(1, length, sampleRate);
// Create synth chain in offline context
const offMasterGain = offlineCtx.createGain();
offMasterGain.gain.value = 0.2;
const offFilter = offlineCtx.createBiquadFilter();
offFilter.type = "lowpass";
offFilter.frequency.value = parseFloat(filterCutoffInput.value);
offMasterGain.connect(offFilter);
offFilter.connect(offlineCtx.destination);
// For LFO we skip for simplicity in export
// Play notes in offline context
let curTime = 0;
for (const ev of events) {
for (const n of ev.notes){
let freq = 0;
if (n.note === 'p') {
freq = 0;
} else {
let key = n.note + n.octave;
freq = frequencyMap[key] || 0;
}
if(freq <= 0) continue;
let osc = offlineCtx.createOscillator();
// pulse width wave
let pw = pulseWidthInput.value / 100;
const wave = createPulseWaveOffline(offlineCtx, pw);
osc.setPeriodicWave(wave);
osc.frequency.setValueAtTime(freq, curTime);
let gainNode = offlineCtx.createGain();
gainNode.gain.setValueAtTime(0, curTime);
// ADSR
const attack = parseFloat(attackInput.value);
const decay = parseFloat(decayInput.value);
const sustain = parseFloat(sustainInput.value);
const release = parseFloat(releaseInput.value);
applyADSROffline(gainNode.gain, curTime, ev.duration, attack, decay, sustain, release);
osc.connect(gainNode);
gainNode.connect(offMasterGain);
osc.start(curTime);
osc.stop(curTime + ev.duration + release + 0.1);
}
curTime += ev.duration;
}
const renderedBuffer = await offlineCtx.startRendering();
// Convert renderedBuffer to WAV
const wavBlob = bufferToWavBlob(renderedBuffer);
const url = URL.createObjectURL(wavBlob);
const a = document.createElement('a');
a.href = url;
a.download = 'rtttl_synth.wav';
a.click();
statusDiv.textContent = "WAV exported!";
} catch(e){
statusDiv.textContent = "Error exporting WAV: " + e.message;
}
}
// Offline create pulse wave helper
function createPulseWaveOffline(ctx, pulseWidth=0.5){
const real = new Float32Array(16);
const imag = new Float32Array(16);
for(let n=1; n<16; n+=2){
real[n] = 4 / (n * Math.PI) * Math.sin(n * Math.PI * pulseWidth);
imag[n] = 0;
}
return ctx.createPeriodicWave(real, imag);
}
// Offline ADSR gain automation
function applyADSROffline(param, startTime, duration, attack, decay, sustain, release) {
const attackEnd = startTime + attack;
const decayEnd = attackEnd + decay;
const releaseStart = startTime + duration;
param.setValueAtTime(0, startTime);
param.linearRampToValueAtTime(1, attackEnd);
param.linearRampToValueAtTime(sustain, decayEnd);
param.setValueAtTime(sustain, releaseStart);
param.linearRampToValueAtTime(0, releaseStart + release);
}
// Buffer to WAV file Blob
function bufferToWavBlob(buffer) {
const numOfChan = buffer.numberOfChannels,
length = buffer.length * numOfChan * 2 + 44,
bufferArray = new ArrayBuffer(length),
view = new DataView(bufferArray),
channels = [],
sampleRate = buffer.sampleRate;
// write WAV header
function writeString(view, offset, string) {
for(let i=0; i<string.length; i++){
view.setUint8(offset + i, string.charCodeAt(i));
}
}
let offset =0;
writeString(view, offset, 'RIFF'); offset+=4;
view.setUint32(offset, length - 8, true); offset+=4;
writeString(view, offset, 'WAVE'); offset+=4;
writeString(view, offset, 'fmt '); offset+=4;
view.setUint32(offset, 16, true); offset+=4;
view.setUint16(offset, 1, true); offset+=2;
view.setUint16(offset, numOfChan, true); offset+=2;
view.setUint32(offset, sampleRate, true); offset+=4;
view.setUint32(offset, sampleRate * 2 * numOfChan, true); offset+=4;
view.setUint16(offset, numOfChan *2, true); offset+=2;
view.setUint16(offset, 16, true); offset+=2;
writeString(view, offset, 'data'); offset+=4;
view.setUint32(offset, length - offset -4, true); offset+=4;
// write the PCM samples
for(let i=0; i<numOfChan; i++){
channels.push(buffer.getChannelData(i));
}
let interleaved = new Int16Array(buffer.length * numOfChan);
for(let i =0; i< buffer.length; i++){
for(let ch=0; ch<numOfChan; ch++){
let sample = channels[ch][i];
// clamp
sample = Math.max(-1, Math.min(1, sample));
sample = sample < 0 ? sample *0x8000 : sample *0x7FFF;
interleaved[i*numOfChan + ch] = sample;
}
}
// Write interleaved data to buffer
for(let i=0; i< interleaved.length; i++){
view.setInt16(offset, interleaved[i], true);
offset +=2;
}
return new Blob([bufferArray], {type:'audio/wav'});
}
// Set hash for sharing (optional)
function updateHash() {
let base64 = btoa(encodeURIComponent(rtttlInput.value));
location.hash = "#/" + base64;
}
// Load from hash on page load
function loadFromHash(){
if(location.hash.startsWith('#/')){
try {
let base64 = location.hash.slice(2);
let decoded = decodeURIComponent(atob(base64));
rtttlInput.value = decoded;
} catch(e){}
}
}
// Event listeners
playBtn.onclick = () => {
if (!isPlaying) scheduleNotes();
};
stopBtn.onclick = stopPlayback;
copyBtn.onclick = copyRTTTL;
exportBtn.onclick = exportWav;
loopCheckbox.onchange = () => {
loop = loopCheckbox.checked;
};
rtttlInput.onchange = updateHash;
attackInput.onchange = onParameterChange;
decayInput.onchange = onParameterChange;
sustainInput.onchange = onParameterChange;
releaseInput.onchange = onParameterChange;
pulseWidthInput.oninput = onParameterChange;
filterCutoffInput.oninput = onParameterChange;
lfoRateInput.onchange = onParameterChange;
flangerDepthInput.onchange = onParameterChange;
loadFromHash();
})();
</script>
</body>
</html>
How it works:
-
Input RTTTL string, e.g.:
Entertainer:d=4,o=5,b=140:8d,8d+,8d+,8d
-
Parse and play notes, including chords (notes joined with +).
-
ADSR envelope applied on each note.
-
Pulse width adjustable pulse wave oscillator.
-
Filter with cutoff frequency, modulated by LFO.
-
Simple flanger effect (delay line modulated by sine LFO).
-
Loop playback when enabled.
-
Export full playback as a WAV file offline.
-
Copy RTTTL string to clipboard.
-
URL is updated with base64 encoded RTTTL string for sharing (#/ hash-based sharing).
To improve / extend:
-
Better RTTTL parsing for dotted notes and note length override per note.
-
More effects and oscillators.
-
UI enhancements and better visualization.
-
Multiple instrument presets.
If you want, I can help you extend this boilerplate with specific features or more polished UI. Just ask!