html rtttl parser chord "+" loop copy custom adsr osc filter pulse width update synth…
- User
html rtttl parser chord "+" loop copy custom adsr osc filter pulse width update synth share "#/ (hash to id)" export wav
- Assistant
html rtttl parser chord "+" loop copy custom adsr osc filter pulse width update synth share "#/ (hash to id)" export wav
You want a complete solution in HTML/JavaScript that can:
# (hash) symbols in note names to valid HTML IDs (since # is not allowed in IDs)This is quite a feature-rich synthesizer/player.
I'll provide you with a basic but expandable framework:
+ separates notes).RTTTL parsing: RTTTL strings have format
Name:d=duration,o=octave,b=bpm:note, note, note...
We'll parse the header and then the sequence.
Chords: notes separated by + mean play these simultaneously.
Loop/Copy: UI can allow selecting a range or looping the entire sequence.
Synth: Web Audio API oscillators, with:
# to ID: When using notes as IDs or keys, replace # with sharp or _sharp (example).
WAV export: Use OfflineAudioContext to render audio and convert buffer to WAV blob and download.
Share: Encode RTTTL string in URL or localStorage.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>RTTTL Synth with Chords, ADSR, Export WAV</title>
<style>
body { font-family: sans-serif; margin: 1em; max-width: 700px; }
textarea { width: 100%; height: 120px; font-family: monospace; }
label { display: block; margin: 0.5em 0 0.2em; }
input, button, select { margin-right: 1em; }
.controls { margin: 1em 0; }
</style>
</head>
<body>
<h1>RTTTL Synthesizer with Chords, ADSR, WAV Export</h1>
<label for="rtttl">Enter RTTTL String:</label>
<textarea id="rtttl" spellcheck="false">Enter your RTTTL here...</textarea>
<div class="controls">
<button id="parsePlayBtn">Parse & Play</button>
<button id="stopBtn" disabled>Stop</button>
<button id="exportWavBtn" disabled>Export WAV</button>
</div>
<h2>ADSR Envelope</h2>
<div>
<label for="attack">Attack (s):</label>
<input id="attack" type="number" step="0.01" min="0" value="0.05">
<label for="decay">Decay (s):</label>
<input id="decay" type="number" step="0.01" min="0" value="0.1">
<label for="sustain">Sustain (0-1):</label>
<input id="sustain" type="number" step="0.1" min="0" max="1" value="0.7">
<label for="release">Release (s):</label>
<input id="release" type="number" step="0.01" min="0" value="0.3">
</div>
<h2>Synth Settings</h2>
<div>
<label for="oscType">Oscillator Type:</label>
<select id="oscType">
<option>square</option>
<option>sine</option>
<option>triangle</option>
<option>sawtooth</option>
</select>
<label for="pulseWidth">Pulse Width (for square, 0.1-0.9):</label>
<input type="number" id="pulseWidth" step="0.01" min="0.1" max="0.9" value="0.5">
</div>
<script>
// Globals
let audioCtx = null;
let masterGain = null;
let isPlaying = false;
let scheduledEvents = [];
let startTime = 0;
// Constants & Utils
const noteFreqs = {
'c': 16.35,
'c#': 17.32,
'd': 18.35,
'd#': 19.45,
'e': 20.60,
'f': 21.83,
'f#': 23.12,
'g': 24.50,
'g#': 25.96,
'a': 27.50,
'a#': 29.14,
'b': 30.87
};
const NOTES = ['c','c#','d','d#','e','f','f#','g','g#','a','a#','b'];
// RTTTL parsing with chords support (+)
function parseRTTTL(rtttl) {
// Split header and notes
let [nameAndParams, notesPart] = rtttl.split(':', 3).slice(1);
if(!notesPart) throw "Invalid RTTTL format";
let parts = rtttl.split(':');
if(parts.length < 3) throw "Invalid RTTTL format";
let name = parts[0].trim();
let defaultsText = parts[1];
let notesText = parts[2];
// Parse defaults (d= duration, o=octave, b=bpm)
let defaults = { d:4, o:6, b:63 };
defaultsText.split(',').forEach(p=>{
let [k,v] = p.split('=');
if(k && v) defaults[k.trim()] = v.trim();
});
// compute note duration base
let bpm = parseInt(defaults.b);
if(isNaN(bpm)) bpm = 63;
let wholeNoteDuration = 60 / bpm * 4; // in seconds
// Parse notes sequence
let notes = [];
let tokens = notesText.split(',');
tokens.forEach(tok => {
tok = tok.trim().toLowerCase();
// Check for chord:
let chordNotes = tok.split('+');
// Each chord note parses as normal RTTTL note;
let chord = chordNotes.map(n=>{
return parseRTTTLNote(n, defaults, wholeNoteDuration);
});
notes.push(chord);
});
return {name, bpm, defaults, notes};
}
function parseRTTTLNote(noteStr, defaults, wholeNoteDuration) {
// '16a#6.' => duration + note + octave + dot
// Regex to parse: (duration)?(note)(#?)(octave)?(.?)
// notes: c,d,e,f,g,a,b,p Pause
let regex = /^(\d+)?([a-gp])(#?)(\d+)?(\.*)$/;
let m = regex.exec(noteStr);
if(!m) throw "Invalid note " + noteStr;
let [_, dur, note, sharp, octave, dots] = m;
let duration = dur ? parseInt(dur) : defaults.d;
let baseOctave = octave ? parseInt(octave) : defaults.o;
// compute note duration in seconds, considering dots (each dot adds 50%)
let durationSeconds = wholeNoteDuration / duration;
if(dots) {
for(let i=0; i<dots.length; i++) {
durationSeconds += durationSeconds / 2 ** (i+1);
}
}
// Handle pause/rest note
if(note==='p') return {freq:null, duration: durationSeconds};
// Note name with optional sharp
let noteName = note + (sharp ? '#' : '');
// Calculate frequency for octave
// noteFreqs base octave = 0 (16.35Hz for C)
// Octave shifts frequency by * 2^(octave)
let baseFreq = noteFreqs[noteName];
if(!baseFreq) throw "Invalid note " + noteName;
let freq = baseFreq * Math.pow(2, baseOctave);
return {freq, duration: durationSeconds};
}
// Create oscillator with pulse width modulation
// WebAudio square oscillator doesn't support pulse width; simulate with PWM oscillator or custom
function createOscillator(ctx, type, freq, pulseWidth=0.5) {
if(type === 'square' && pulseWidth !== 0.5) {
// Use PWM - workaround: use a PeriodicWave with custom waveform
// Generate PWM wave
let real = new Float32Array(4);
let imag = new Float32Array(4);
real[0] = 0;
imag[0] = 0;
// Fourier series for PWM waveform
for(let n = 1; n < 4; n++) {
real[n] = (2/ (n * Math.PI)) * Math.sin(n * Math.PI * pulseWidth);
imag[n] = 0;
}
let wave = ctx.createPeriodicWave(real, imag);
let osc = ctx.createOscillator();
osc.setPeriodicWave(wave);
osc.frequency.value = freq;
return osc;
} else {
let osc = ctx.createOscillator();
osc.type = type;
osc.frequency.value = freq;
return osc;
}
}
// ADSR Envelope automation on GainNode
function applyADSR(gainNode, startTime, duration, attack, decay, sustain, release) {
let gain = gainNode.gain;
gain.cancelScheduledValues(startTime);
gain.setValueAtTime(0, startTime);
gain.linearRampToValueAtTime(1, startTime + attack);
gain.linearRampToValueAtTime(sustain, startTime + attack + decay);
gain.setValueAtTime(sustain, startTime + duration);
gain.linearRampToValueAtTime(0, startTime + duration + release);
}
// Replace # in note names with 'sharp' for IDs
function sanitizeId(str) {
return str.replace(/#/g, 'sharp');
}
// Play the RTTTL tune with chords and adsr
async function playRTTTL(parsed, adsr, synthSettings) {
if(isPlaying) stopPlaying();
if(!audioCtx) {
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
}
masterGain = audioCtx.createGain();
masterGain.gain.value = 0.3;
masterGain.connect(audioCtx.destination);
let currentTime = audioCtx.currentTime + 0.1; // Start after 100ms delay
startTime = currentTime;
scheduledEvents = [];
const {attack, decay, sustain, release} = adsr;
const {oscType, pulseWidth} = synthSettings;
for(const chord of parsed.notes) {
// chord is an array of notes played simultaneously
// chord may be single note or multiple notes
// chord is array, if freq=null that means rest note
// Duration is taken from first note (all chord notes must have same duration)
let chordDuration = chord[0].duration;
chord.forEach(note => {
if(note.freq === null) return; // rest
let osc = createOscillator(audioCtx, oscType, note.freq, pulseWidth);
let gainNode = audioCtx.createGain();
// Filter node (optional)
let filter = audioCtx.createBiquadFilter();
filter.type = 'lowpass';
filter.frequency.setValueAtTime(1000, currentTime); // static for now
osc.connect(gainNode);
gainNode.connect(filter);
filter.connect(masterGain);
// ADSR envelope
applyADSR(gainNode, currentTime, chordDuration, attack, decay, sustain, release);
osc.start(currentTime);
osc.stop(currentTime + chordDuration + release + 0.1);
scheduledEvents.push({osc, gainNode, filter});
});
currentTime += chordDuration; // next chord start time
}
isPlaying = true;
// Disable Play button, enable Stop and Export
document.getElementById('parsePlayBtn').disabled = true;
document.getElementById('stopBtn').disabled = false;
document.getElementById('exportWavBtn').disabled = false;
// Auto stop cleanup
setTimeout(()=> {
stopPlaying();
}, (currentTime - audioCtx.currentTime) * 1000 + 500);
}
function stopPlaying() {
if(!isPlaying) return;
scheduledEvents.forEach(e=>{
try {
e.osc.stop();
} catch(e) {}
});
if(masterGain) masterGain.disconnect();
masterGain = null;
isPlaying = false;
scheduledEvents = [];
document.getElementById('parsePlayBtn').disabled = false;
document.getElementById('stopBtn').disabled = true;
// We do not disable export since audioCtx still exists
}
// Export to WAV using OfflineAudioContext
async function exportWAV(parsed, adsr, synthSettings) {
// Calculate total duration (sum of note durations + release)
let totalDuration = 0;
parsed.notes.forEach(chord => {
totalDuration += chord[0].duration;
});
totalDuration += adsr.release + 0.5;
// Create offline context
const sampleRate = 44100;
let offlineCtx = new OfflineAudioContext(1, sampleRate * totalDuration, sampleRate);
let offlineGain = offlineCtx.createGain();
offlineGain.gain.value = 0.3;
offlineGain.connect(offlineCtx.destination);
let currentTime = 0;
const {attack, decay, sustain, release} = adsr;
const {oscType, pulseWidth} = synthSettings;
for(const chord of parsed.notes) {
let chordDuration = chord[0].duration;
chord.forEach(note => {
if(note.freq === null) return;
let osc = createOscillator(offlineCtx, oscType, note.freq, pulseWidth);
let gainNode = offlineCtx.createGain();
let filter = offlineCtx.createBiquadFilter();
filter.type = 'lowpass';
filter.frequency.setValueAtTime(1000, currentTime); // static
osc.connect(gainNode);
gainNode.connect(filter);
filter.connect(offlineGain);
// ADSR envelope
applyADSR(gainNode, currentTime, chordDuration, attack, decay, sustain, release);
osc.start(currentTime);
osc.stop(currentTime + chordDuration + release + 0.1);
});
currentTime += chordDuration;
}
// Render
let renderedBuffer = await offlineCtx.startRendering();
// Encode WAV and download
let wavBlob = encodeWAV(renderedBuffer);
let url = URL.createObjectURL(wavBlob);
let a = document.createElement('a');
a.href = url;
a.download = (parsed.name || 'rtttl') + ".wav";
document.body.appendChild(a);
a.click();
setTimeout(()=> {
document.body.removeChild(a);
URL.revokeObjectURL(url);
}, 100);
}
// WAV encoder (PCM 16-bit)
function encodeWAV(audioBuffer) {
let numChannels = audioBuffer.numberOfChannels;
let sampleRate = audioBuffer.sampleRate;
let format = 1; // PCM
let bitDepth = 16;
let samples = audioBuffer.length;
let blockAlign = numChannels * bitDepth / 8;
let byteRate = sampleRate * blockAlign;
let dataSize = samples * blockAlign;
let buffer = new ArrayBuffer(44 + dataSize);
let view = new DataView(buffer);
// RIFF header
writeString(view, 0, 'RIFF');
view.setUint32(4, 36 + dataSize, true);
writeString(view, 8, 'WAVE');
// fmt chunk
writeString(view, 12, 'fmt ');
view.setUint32(16, 16, true); // chunk size
view.setUint16(20, format, true); // format PCM
view.setUint16(22, numChannels, true);
view.setUint32(24, sampleRate, true);
view.setUint32(28, byteRate, true);
view.setUint16(32, blockAlign, true);
view.setUint16(34, bitDepth, true);
// data chunk
writeString(view, 36, 'data');
view.setUint32(40, dataSize, true);
// Write interleaved samples
let offset = 44;
let channels = [];
for(let i=0; i<numChannels; i++) {
channels.push(audioBuffer.getChannelData(i));
}
for(let i=0; i<samples; i++) {
for(let ch=0; ch<numChannels; ch++) {
let sample = channels[ch][i];
// Clamp & convert float to 16-bit PCM
sample = Math.max(-1, Math.min(1, sample));
let intSample = sample < 0 ? sample * 0x8000 : sample * 0x7FFF;
view.setInt16(offset, intSample, true);
offset += 2;
}
}
return new Blob([buffer], {type:'audio/wav'});
}
function writeString(dataview, offset, str) {
for(let i=0; i<str.length; i++) {
dataview.setUint8(offset+i, str.charCodeAt(i));
}
}
// --- UI ---
const rtttlInput = document.getElementById('rtttl');
const parsePlayBtn = document.getElementById('parsePlayBtn');
const stopBtn = document.getElementById('stopBtn');
const exportWavBtn = document.getElementById('exportWavBtn');
function getADSR() {
return {
attack: parseFloat(document.getElementById('attack').value),
decay: parseFloat(document.getElementById('decay').value),
sustain: parseFloat(document.getElementById('sustain').value),
release: parseFloat(document.getElementById('release').value),
};
}
function getSynthSettings() {
return {
oscType: document.getElementById('oscType').value,
pulseWidth: parseFloat(document.getElementById('pulseWidth').value),
};
}
parsePlayBtn.addEventListener('click', ()=> {
let rtttl = rtttlInput.value.trim();
if(rtttl.length === 0) {
alert("Please enter an RTTTL string");
return;
}
try {
let parsed = parseRTTTL(rtttl);
let adsr = getADSR();
let synthSettings = getSynthSettings();
// Resume audio context on browsers requiring user interaction
if(!audioCtx) {
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
}
if(audioCtx.state === 'suspended') {
audioCtx.resume();
}
playRTTTL(parsed, adsr, synthSettings);
} catch(e) {
alert("Error parsing RTTTL: " + e);
}
});
stopBtn.addEventListener('click', ()=> {
stopPlaying();
});
exportWavBtn.addEventListener('click', async ()=> {
let rtttl = rtttlInput.value.trim();
if(rtttl.length === 0) {
alert("Please enter an RTTTL string");
return;
}
try {
let parsed = parseRTTTL(rtttl);
let adsr = getADSR();
let synthSettings = getSynthSettings();
await exportWAV(parsed, adsr, synthSettings);
} catch(e) {
alert("Error parsing or exporting: " + e);
}
});
</script>
</body>
</html>
Enter your RTTTL here... to test, replace with something valid likeEnter your RTTTL here... -> Replace with:mario:d=4,o=5,b=140:c,e,g+e,c6g+e plays G and E simultaneously.# in note names by replacing with 'sharp' internally.Let me know if you want help adding additional features!