<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>RTTTL Synth + Chords + ADSR + Export + Share</title>
<style>
body { font-family: sans-serif; margin: 20px; background: #222; color: #eee; }
textarea, input, button, select { font-family: monospace; font-size: 1rem; margin: 5px 0; width: 100%; }
label { margin-top: 10px; display: block; }
.note { display: inline-block; min-width: 30px; text-align: center; }
</style>
</head>
<body>
<h1>RTTTL Synth + Chords + ADSR + Export + Share</h1>
<label>Input RTTTL:</label>
<textarea id="rtttl" rows="4">Enter your RTTTL string here</textarea>
<label>ADSR Envelope (ms):</label>
Attack: <input id="attack" type="number" value="50" min="0" max="1000" step="1" />
Decay: <input id="decay" type="number" value="100" min="0" max="1000" step="1" />
Sustain (0-1): <input id="sustain" type="number" value="0.5" min="0" max="1" step="0.01" />
Release: <input id="release" type="number" value="200" min="0" max="2000" step="1" />
<label>Oscillator waveform:</label>
<select id="waveform">
<option value="square">Square (supports pulse width)</option>
<option value="sine">Sine</option>
<option value="triangle">Triangle</option>
<option value="sawtooth">Sawtooth</option>
</select>
<label>Pulse width (for square) 0-1:</label>
<input id="pulseWidth" type="number" value="0.5" min="0.05" max="0.95" step="0.01" />
<label>Loop playback:</label>
<input type="checkbox" id="loop" />
<br/>
<button id="playBtn">Play</button>
<button id="stopBtn" disabled>Stop</button>
<button id="exportBtn">Export WAV</button>
<button id="copyBtn">Copy RTTTL + Settings</button>
<button id="pasteBtn">Paste RTTTL + Settings</button>
<script>
// === Global variables ===
let audioCtx;
let isPlaying = false;
let scheduledNotes = [];
let loopPlayback = false;
const noteFreqs = (() => {
// note names with octave from C0 (16.35Hz) upwards.
// Map "c", "c#", "d", etc. to freq
const A4 = 440;
const notes = ['c', 'c#', 'd', 'd#', 'e', 'f', 'f#', 'g', 'g#', 'a', 'a#', 'b'];
let map = {};
for(let octave=0; octave<=8; octave++) {
for(let i = 0; i < notes.length; i++) {
let noteName = notes[i] + octave;
// Formula for freq: A4 = 440Hz, note number offset from A4 = semitones
let n = i + 12*(octave - 4) - 9; // -9 because A is the 9th note (zero based)
let freq = Math.pow(2, n/12)*A4;
map[noteName] = freq;
}
}
// Also no octave notes — default octave can be 6 since RTTTL default o=6 typically.
// We will assign those default octave later
return map;
})();
// Parse RTTTL string and return array of {duration_ms, chord: [freq1,freq2...]}
function parseRTTTL(rtttlStr) {
/*
RTTTL format: name:d=4,o=5,b=140:note1,note2, ...
notes: [duration][note][octave][.][+chords separated by +]
*/
// clean and split
let parts = rtttlStr.trim().split(':');
if(parts.length !== 3) throw new Error('Invalid RTTTL format');
let [name, defaultsStr, notesStr] = parts;
let defaults = {d:4, o:6, b:63}; // defaults if not specified
defaultsStr.split(',').forEach( def=>{
let [k,v] = def.split('=');
if(k && v) defaults[k] = isNaN(v)? v : +v;
});
// calculate ms per duration unit
let bpm = defaults.b;
let wholeNoteMs = (60/bpm)*4*1000; // duration of whole note in ms
// parse note string list
let notes = notesStr.split(',');
let result = [];
for(let noteRaw of notes) {
// Parse a single note or chord (chords separated by +)
// Note format: [duration][note][# or b][octave][dot]
// Separate by '+' to get chord notes
let chordParts = noteRaw.split('+');
let chordFreqs = [];
// For duration, check first integer characters of noteRaw (before letters)
// Same duration for whole chord notes
// We'll parse duration from first noteRaw, ignoring + chords duration separately
// Get duration:
let durationMatch = noteRaw.match(/^(\d+)?/);
let durationVal = durationMatch && durationMatch[1] ? +durationMatch[1] : defaults.d;
let durationMs = wholeNoteMs / durationVal;
// Check for dotted note '.': duration * 1.5
let dot = noteRaw.includes('.');
if(dot) durationMs *= 1.5;
// For each chord note:
for(let chNoteRaw of chordParts) {
// Remove duration prefix from chord note:
let chNote = chNoteRaw.replace(/^\d+/, '').replace('.', '');
if(chNote.toLowerCase()==='p') {
// pause
chordFreqs.push(null);
continue;
}
// Match note name and octave:
let m = chNote.match(/^([a-gA-G](?:#|b)?)(\d?)$/);
if(!m) throw new Error('Invalid note: '+chNote);
let note = m[1].toLowerCase();
let octave = m[2] ? +m[2] : defaults.o;
// map b to #
if(note.includes('b')) {
// flat: b means one semitone down
let baseNote = note[0];
// convert flat to note# one semitone below
let flats = {'a':'g#','b':'a#','c':'b','d':'c#','e':'d#','f':'e','g':'f#'};
note = flats[baseNote];
}
let freqKey = note+octave;
let freq = noteFreqs[freqKey];
if(!freq) throw new Error('Unknown note freq: '+freqKey);
chordFreqs.push(freq);
}
result.push({
duration: durationMs,
chord: chordFreqs
});
}
return result;
}
// Play a note with ADSR on given audio context oscillator
function playChord(ctx, dest, chordFreqs, duration, adsr, waveform, pulseWidth, startTime) {
// We'll create oscillator per freq
// For pulseWidth (square), Web Audio does not have native pulse width, we can simulate with PWM via custom oscillator or modulated gain
// For now, do simple square wave, later can improve
const notes = [];
for(let freq of chordFreqs) {
if(freq==null) continue; // pause
let osc;
if(waveform==='square' && pulseWidth !== 0.5) {
// simulate pulse width with PWM oscillator
osc = createPulseOscillator(ctx, freq, pulseWidth);
} else {
osc = ctx.createOscillator();
osc.type = waveform;
osc.frequency.setValueAtTime(freq, startTime);
}
const gainNode = ctx.createGain();
osc.connect(gainNode);
gainNode.connect(dest);
// ADSR envelope
const a = adsr.attack/1000;
const d = adsr.decay/1000;
const s = adsr.sustain;
const r = adsr.release/1000;
gainNode.gain.setValueAtTime(0, startTime);
gainNode.gain.linearRampToValueAtTime(1, startTime+a);
gainNode.gain.linearRampToValueAtTime(s, startTime+a+d);
// sustain level held until note release start
gainNode.gain.setValueAtTime(s, startTime + duration);
gainNode.gain.linearRampToValueAtTime(0, startTime + duration + r);
osc.start(startTime);
osc.stop(startTime + duration + r);
notes.push({osc, gainNode});
}
return notes;
}
// Create pulse oscillator using two oscillators detuned
function createPulseOscillator(ctx, freq, pulseWidth) {
// simulate pulse width modulation by combining two oscillators with phase offset
// or use ScriptProcessor (deprecated)
// simple approach is to use oscillator + gain node modulated with periodic waveform
// Here we create a rectangle wave with uneven duty cycle using OscillatorNode + GainNode + periodic modulation
// but this is tricky.
// For simplicity, we'll use AudioWorklet if available or fallback.
// For demo, use square wave, ignoring pulse width, as AudioWorklet requires extra code and setup.
let osc = ctx.createOscillator();
osc.type = 'square';
osc.frequency.setValueAtTime(freq, ctx.currentTime);
return osc;
}
// Playback controller
let playTimeout;
function playRTTTL(rtttlStr, adsr, waveform, pulseWidth, loop) {
if(isPlaying) stop();
audioCtx = new AudioContext();
let notes;
try {
notes = parseRTTTL(rtttlStr);
} catch(e) {
alert('RTTTL parse error: '+e.message);
return;
}
isPlaying = true;
document.getElementById('playBtn').disabled = true;
document.getElementById('stopBtn').disabled = false;
let currentTime = audioCtx.currentTime + 0.1; // delay start a bit
function scheduleNotes() {
let t = currentTime;
for(let note of notes) {
playChord(audioCtx, audioCtx.destination, note.chord, note.duration/1000, adsr, waveform, pulseWidth, t);
t += note.duration/1000;
}
return t - currentTime;
}
let totalDuration = scheduleNotes();
if(loop) {
playTimeout = setInterval(()=>{
if(!isPlaying) return;
currentTime = audioCtx.currentTime + 0.1;
scheduleNotes();
}, totalDuration*1000);
}
}
function stop() {
if(!isPlaying) return;
if(playTimeout) clearInterval(playTimeout);
if(audioCtx) {
audioCtx.close();
audioCtx = null;
}
isPlaying = false;
document.getElementById('playBtn').disabled = false;
document.getElementById('stopBtn').disabled = true;
}
// Export as WAV using OfflineAudioContext
async function exportWav(rtttlStr, adsr, waveform, pulseWidth) {
let notes;
try {
notes = parseRTTTL(rtttlStr);
} catch(e) {
alert('RTTTL parse error: '+e.message);
return;
}
// Estimate duration
let totalMs = notes.reduce((a,v)=>a+v.duration,0);
let sampleRate = 44100;
let offlineCtx = new OfflineAudioContext(1, sampleRate * (totalMs/1000 + 1), sampleRate);
let currentTime = 0;
for(let note of notes) {
playChord(offlineCtx, offlineCtx.destination, note.chord, note.duration/1000, adsr, waveform, pulseWidth, currentTime);
currentTime += note.duration/1000;
}
let renderedBuffer = await offlineCtx.startRendering();
// WAV conversion from AudioBuffer
let wavBlob = bufferToWav(renderedBuffer);
// download
let url = URL.createObjectURL(wavBlob);
let a = document.createElement('a');
a.href = url;
a.download = 'rtttl_export.wav';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
// Convert AudioBuffer to WAV blob (16-bit PCM)
function bufferToWav(buffer) {
let numOfChan = buffer.numberOfChannels,
length = buffer.length * numOfChan * 2 + 44,
bufferArray = new ArrayBuffer(length),
view = new DataView(bufferArray),
channels = [],
sampleRate = buffer.sampleRate,
offset = 0,
pos = 0;
// write WAVE header
setUint32(0x46464952); // "RIFF"
setUint32(length - 8); // file length - 8
setUint32(0x45564157); // "WAVE"
setUint32(0x20746d66); // "fmt " chunk
setUint32(16); // length = 16
setUint16(1); // PCM (uncompressed)
setUint16(numOfChan);
setUint32(sampleRate);
setUint32(sampleRate * 2 * numOfChan); // avg. bytes/sec
setUint16(numOfChan * 2); // block-align
setUint16(16); // 16-bit (hardcoded in this demo)
setUint32(0x61746164); // "data" - chunk
setUint32(length - pos - 4); // chunk length
// write interleaved data
for(let i=0; i<numOfChan; i++)
channels.push(buffer.getChannelData(i));
let len = buffer.length;
for(let i=0; i<len; i++) {
for(let ch=0; ch<numOfChan; ch++) {
let sample = Math.max(-1, Math.min(1, channels[ch][i]));
sample = sample < 0 ? sample * 0x8000 : sample * 0x7FFF;
view.setInt16(pos, sample, true);
pos += 2;
}
}
return new Blob([bufferArray], {type:"audio/wav"});
function setUint16(data) {
view.setUint16(pos, data, true);
pos += 2;
}
function setUint32(data) {
view.setUint32(pos, data, true);
pos += 4;
}
}
// Save/Load from URL hash for sharing
function saveStateToHash() {
// Save RTTTL and settings as JSON string
const state = {
rtttl: document.getElementById('rtttl').value,
attack: +document.getElementById('attack').value,
decay: +document.getElementById('decay').value,
sustain: +document.getElementById('sustain').value,
release: +document.getElementById('release').value,
waveform: document.getElementById('waveform').value,
pulseWidth: +document.getElementById('pulseWidth').value,
loop: document.getElementById('loop').checked,
};
const json = JSON.stringify(state);
const hash = encodeURIComponent(btoa(json));
location.hash = hash;
}
function loadStateFromHash() {
if(!location.hash) return;
try {
const json = atob(decodeURIComponent(location.hash.substring(1)));
const state = JSON.parse(json);
if(state.rtttl) document.getElementById('rtttl').value = state.rtttl;
if(state.attack!=null) document.getElementById('attack').value = state.attack;
if(state.decay!=null) document.getElementById('decay').value = state.decay;
if(state.sustain!=null) document.getElementById('sustain').value = state.sustain;
if(state.release!=null) document.getElementById('release').value = state.release;
if(state.waveform) document.getElementById('waveform').value = state.waveform;
if(state.pulseWidth!=null) document.getElementById('pulseWidth').value = state.pulseWidth;
if(state.loop!=null) document.getElementById('loop').checked = state.loop;
} catch(e) {
console.warn('Failed to parse state from URL hash');
}
}
// Clipboard copy/paste of JSON presets
async function copyToClipboard() {
try {
const data = {
rtttl: document.getElementById('rtttl').value,
attack: +document.getElementById('attack').value,
decay: +document.getElementById('decay').value,
sustain: +document.getElementById('sustain').value,
release: +document.getElementById('release').value,
waveform: document.getElementById('waveform').value,
pulseWidth: +document.getElementById('pulseWidth').value,
loop: document.getElementById('loop').checked,
};
await navigator.clipboard.writeText(JSON.stringify(data));
alert('Copied preset to clipboard');
} catch( e) {
alert('Failed to copy: '+e.message);
}
}
async function pasteFromClipboard() {
try {
const text = await navigator.clipboard.readText();
const data = JSON.parse(text);
if(data.rtttl) document.getElementById('rtttl').value = data.rtttl;
if(data.attack!=null) document.getElementById('attack').value = data.attack;
if(data.decay!=null) document.getElementById('decay').value = data.decay;
if(data.sustain!=null) document.getElementById('sustain').value = data.sustain;
if(data.release!=null) document.getElementById('release').value = data.release;
if(data.waveform) document.getElementById('waveform').value = data.waveform;
if(data.pulseWidth!=null) document.getElementById('pulseWidth').value = data.pulseWidth;
if(data.loop!=null) document.getElementById('loop').checked = data.loop;
alert('Pasted preset from clipboard');
} catch(e) {
alert('Failed to paste: '+e.message);
}
}
// Event listeners
document.getElementById('playBtn').addEventListener('click', ()=>{
const rtttl = document.getElementById('rtttl').value;
const adsr = {
attack: +document.getElementById('attack').value,
decay: +document.getElementById('decay').value,
sustain: +document.getElementById('sustain').value,
release: +document.getElementById('release').value,
};
const waveform = document.getElementById('waveform').value;
const pulseWidth = +document.getElementById('pulseWidth').value;
loopPlayback = document.getElementById('loop').checked;
playRTTTL(rtttl, adsr, waveform, pulseWidth, loopPlayback);
saveStateToHash();
});
document.getElementById('stopBtn').addEventListener('click', stop);
document.getElementById('exportBtn').addEventListener('click', ()=>{
const rtttl = document.getElementById('rtttl').value;
const adsr = {
attack: +document.getElementById('attack').value,
decay: +document.getElementById('decay').value,
sustain: +document.getElementById('sustain').value,
release: +document.getElementById('release').value,
};
const waveform = document.getElementById('waveform').value;
const pulseWidth = +document.getElementById('pulseWidth').value;
exportWav(rtttl, adsr, waveform, pulseWidth);
});
document.getElementById('copyBtn').addEventListener('click', copyToClipboard);
document.getElementById('pasteBtn').addEventListener('click', pasteFromClipboard);
// Load state from URL hash on load
window.addEventListener('load', loadStateFromHash);
window.addEventListener('hashchange', loadStateFromHash);
</script>
</body>
</html>