It looks like you want to build a web-based music synthesizer or player that can:
That's quite a comprehensive project! I can help you with a simplified but functional example that addresses these features incrementally.
Notes are space/comma separated and can be chords with "+".
Let's start by parsing an RTTTL string into a playable note sequence.
Add a loop play feature.
We can store the RTTTL string in the URL hash with base64 encoding.
Use offlineAudioContext and export offline buffer as WAV data URL, triggered on button.
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 + Export</title>
<style>
body { font-family: sans-serif; padding: 1em; background: #222; color: #eee; }
input, textarea, button, select { font-size: 1em; margin: 0.2em 0; width: 100%; }
label { font-weight: bold; margin-top: 1em; display: block; }
.controls { max-width: 600px; margin: auto; }
</style>
</head>
<body>
<div class="controls">
<label for="rtttl">RTTTL String:</label>
<textarea id="rtttl" rows="3"></textarea>
<label for="adsr">ADSR (ms): Attack, Decay, Sustain(0-1), Release</label>
<input type="text" id="adsr" value="0,100,0.5,300" />
<label for="waveform">Oscillator Type</label>
<select id="waveform">
<option value="square">Square</option>
<option value="sine">Sine</option>
<option value="sawtooth">Sawtooth</option>
<option value="triangle">Triangle</option>
<option value="pulse">Pulse (via custom)</option>
</select>
<label for="pulseWidth">Pulse Width (only if Pulse type) (0.05-0.95)</label>
<input type="range" id="pulseWidth" min="0.05" max="0.95" step="0.01" value="0.5" />
<label for="filterCutoff">Filter Cutoff Frequency (Hz)</label>
<input type="range" id="filterCutoff" min="100" max="20000" step="1" value="10000" />
<label><input type="checkbox" id="loop" /> Loop</label>
<button id="playButton">Play</button>
<button id="stopButton" disabled>Stop</button>
<button id="exportWav">Export WAV</button>
<div id="log" style="white-space: pre-wrap; margin-top: 1em; font-size: 0.9em;"></div>
</div>
<script>
(() => {
// Constants
const NOTES_FREQ = (() => {
// A4 = 440Hz, notes relative to A4
let baseFreqs = {
c: -9, d: -7, e: -5, f: -4, g: -2, a: 0, b: 2,
p: null // pause
};
// Compute frequencies for octave n as A4=440*(2^(n-4))
return baseFreqs;
})();
// Helper to get frequency from note letter + octave + accidental (#)
function getFrequency(note, octave) {
if(note === 'p') return 0;
let semitoneDistance = {
c: 0,
'c#': 1, db: 1,
d: 2,
'd#': 3, eb: 3,
e: 4,
f: 5,
'f#': 6, gb: 6,
g: 7,
'g#': 8, ab: 8,
a: 9,
'a#': 10, bb: 10,
b: 11
};
let key = note.toLowerCase();
let semitone = semitoneDistance[key];
if(semitone === undefined) {
return null;
}
let baseFreq = 440 * Math.pow(2, (semitone + (octave - 4)*12 - 9) / 12);
return baseFreq;
}
// Parse RTTTL string: returns array of {duration, notes[]} with freq and duration
// Supports chords using "+" (e.g. c+e+g)
function parseRTTTL(rtttl) {
// Format: name:d=4,o=5,b=140:notes
const [header, notesPart] = rtttl.split(':').slice(1);
let defaults = { d:4, o:6, b:63};
if(!header || !notesPart) return null;
let parts = header.split(',');
parts.forEach(p => {
let [k,v] = p.split('=');
if(k && v) {
if(k==="d" || k==="o" || k==="b") defaults[k] = Number(v);
}
});
let bpm = defaults.b;
let defaultDuration = defaults.d;
let defaultOctave = defaults.o;
let notesRaw = notesPart.split(',');
const wholeNoteDuration = (60 / bpm) * 4; // seconds for whole note
// Parse each note/chord
let sequence = notesRaw.map(item => {
// item example: 16c+e+g, 4p, 8d#
// extract duration (optional), note(s), octave(optional), dotted(optional)
let durationMatch = item.match(/^(\d+)?/);
let duration = durationMatch && durationMatch[1] ? Number(durationMatch[1]) : defaultDuration;
// Remove duration digits
let rest = item.replace(/^\d+/, '');
// Dotted note
let dotted = rest.includes('.');
rest = rest.replace('.', '');
// Notes - split chords by '+'
let notes = rest.split('+').map(noteString => {
// note format: note letter, optional # or b, optional octave number
let match = noteString.match(/^([a-gpA-GP])(#|b)?(\d)?$/);
if(!match) return null;
let note = match[1].toLowerCase();
let accidental = match[2] || '';
let octave = match[3] ? Number(match[3]) : defaultOctave;
let noteName = note + accidental;
return { note: noteName, octave};
});
// Calculate duration seconds
let durSeconds = wholeNoteDuration / duration;
if(dotted) durSeconds *= 1.5;
return { duration: durSeconds, notes };
});
return sequence;
}
// Web Audio Synth
class Synth {
constructor(audioContext, options = {}) {
this.ctx = audioContext;
this.adsr = options.adsr || { attack: 0, decay: 0.1, sustain: 0.7, release: 0.3 };
this.waveform = options.waveform || 'square';
this.pulseWidth = options.pulseWidth || 0.5;
this.filterCutoff = options.filterCutoff || 10000;
this.masterGain = this.ctx.createGain();
this.masterGain.gain.value = 0.3;
this.masterGain.connect(this.ctx.destination);
this._notes = [];
}
// Create oscillator with waveform or pulse custom
_createOscillator(freq) {
if(this.waveform === 'pulse') {
// Custom pulse width oscillator with two oscillators cancelling phase - PWM effect
// Use ScriptProcessor or periodicWave, but here simple PWM via gain node modulating waveform
// Better approach: create a pulse wave with PWM using PeriodicWave
// Create a pulse wave
let real = new Float32Array(2);
let imag = new Float32Array(2);
real[0] = 0;
imag[0] = 0;
real[1] = Math.cos(Math.PI * this.pulseWidth);
imag[1] = Math.sin(Math.PI * this.pulseWidth);
let wave = this.ctx.createPeriodicWave(real, imag);
let osc = this.ctx.createOscillator();
osc.setPeriodicWave(wave);
osc.frequency.value = freq;
return osc;
} else {
let osc = this.ctx.createOscillator();
osc.type = this.waveform;
osc.frequency.value = freq;
return osc;
}
}
playNote(freq, duration) {
const now = this.ctx.currentTime;
if(freq === 0) {
// Pause: simply delay
return new Promise(resolve => {
setTimeout(resolve, duration*1000);
});
}
// Oscillator
const osc = this._createOscillator(freq);
// Filter
const filter = this.ctx.createBiquadFilter();
filter.type = 'lowpass';
filter.frequency.value = this.filterCutoff;
// Gain node for ADSR envelope
const gainNode = this.ctx.createGain();
gainNode.gain.setValueAtTime(0, now);
osc.connect(filter);
filter.connect(gainNode);
gainNode.connect(this.masterGain);
osc.start(now);
// ADSR envelope
let {attack, decay, sustain, release} = this.adsr;
gainNode.gain.cancelScheduledValues(now);
gainNode.gain.setValueAtTime(0, now);
gainNode.gain.linearRampToValueAtTime(1, now + attack);
gainNode.gain.linearRampToValueAtTime(sustain, now + attack + decay);
gainNode.gain.setValueAtTime(sustain, now + duration);
gainNode.gain.linearRampToValueAtTime(0, now + duration + release);
osc.stop(now + duration + release);
return new Promise(resolve => {
osc.onended = () => {
resolve();
};
});
}
// Play chord (simultaneous notes)
playChord(notes, duration) {
// play all notes concurrently, wait for all to finish
const notePromises = notes.map(n => {
let freq = getFrequency(n.note, n.octave);
if(!freq) freq = 0;
return this.playNote(freq, duration);
});
return Promise.all(notePromises);
}
}
// Interface
const rtttlInput = document.getElementById('rtttl');
const playBtn = document.getElementById('playButton');
const stopBtn = document.getElementById('stopButton');
const exportBtn = document.getElementById('exportWav');
const logEl = document.getElementById('log');
const adsrInput = document.getElementById('adsr');
const waveformSelect = document.getElementById('waveform');
const pulseWidthInput = document.getElementById('pulseWidth');
const filterCutoffInput = document.getElementById('filterCutoff');
const loopCheckbox = document.getElementById('loop');
let audioCtx = null;
let synth = null;
let playing = false;
let stopRequested = false;
// Load from hash if present
function loadFromHash() {
if(location.hash.startsWith("#r=")) {
try {
let encoded = location.hash.slice(3);
let decoded = decodeURIComponent(atob(encoded));
rtttlInput.value = decoded;
} catch(e) {
// ignore
}
}
}
loadFromHash();
function saveToHash() {
let val = rtttlInput.value.trim();
if(!val) {
location.hash = "";
return;
}
let encoded = btoa(encodeURIComponent(val));
location.hash = "#r=" + encoded;
}
// Update hash on change
rtttlInput.addEventListener('input', saveToHash);
async function playSequence(sequence, options) {
if(!audioCtx) {
audioCtx = new AudioContext();
}
synth = new Synth(audioCtx, options);
playing = true;
stopRequested = false;
playBtn.disabled = true;
stopBtn.disabled = false;
do {
for(let item of sequence) {
if(stopRequested) break;
await synth.playChord(item.notes, item.duration);
}
} while(loopCheckbox.checked && !stopRequested);
playing = false;
playBtn.disabled = false;
stopBtn.disabled = true;
}
playBtn.addEventListener('click', () => {
if(playing) return;
const rtttl = rtttlInput.value.trim();
if(!rtttl) {
alert('Please enter an RTTTL string.');
return;
}
const sequence = parseRTTTL(rtttl);
if(!sequence) {
alert('Invalid RTTTL string.');
return;
}
let adsrVals = adsrInput.value.split(',').map(x => x.trim());
if(adsrVals.length !== 4) {
alert('ADSR must have 4 values.');
return;
}
let ADSR = {
attack: Number(adsrVals[0])/1000,
decay: Number(adsrVals[1])/1000,
sustain: Number(adsrVals[2]),
release: Number(adsrVals[3])/1000,
};
const waveform = waveformSelect.value;
const pulseWidth = Number(pulseWidthInput.value);
const filterCutoff = Number(filterCutoffInput.value);
playSequence(sequence, { adsr: ADSR, waveform, pulseWidth, filterCutoff });
});
stopBtn.addEventListener('click', () => {
stopRequested = true;
});
// Export WAV file
exportBtn.addEventListener('click', async () => {
const rtttl = rtttlInput.value.trim();
if(!rtttl) {
alert('Enter RTTTL to export.');
return;
}
const sequence = parseRTTTL(rtttl);
if(!sequence) {
alert('Invalid RTTTL.');
return;
}
let adsrVals = adsrInput.value.split(',').map(x => x.trim());
if(adsrVals.length !== 4) {
alert('ADSR must have 4 values.');
return;
}
let ADSR = {
attack: Number(adsrVals[0])/1000,
decay: Number(adsrVals[1])/1000,
sustain: Number(adsrVals[2]),
release: Number(adsrVals[3])/1000,
};
const waveform = waveformSelect.value;
const pulseWidth = Number(pulseWidthInput.value);
const filterCutoff = Number(filterCutoffInput.value);
const lengthSeconds = sequence.reduce((a,c) => a + c.duration, 0) * (loopCheckbox.checked ? 2 : 1) + 1;
logEl.textContent = "Exporting... please wait.";
// OfflineAudioContext for export
const sampleRate = 44100;
const offlineCtx = new OfflineAudioContext(1, lengthSeconds*sampleRate, sampleRate);
class ExportSynth extends Synth {
constructor(ctx, options) {
super(ctx, options);
}
playNote(freq, duration, startTime) {
if(freq === 0) return;
const osc = this._createOscillator(freq);
const filter = this.ctx.createBiquadFilter();
filter.type = 'lowpass';
filter.frequency.value = this.filterCutoff;
const gainNode = this.ctx.createGain();
gainNode.gain.setValueAtTime(0, startTime);
osc.connect(filter);
filter.connect(gainNode);
gainNode.connect(this.masterGain);
this.masterGain.connect(this.ctx.destination);
osc.start(startTime);
let {attack, decay, sustain, release} = this.adsr;
gainNode.gain.cancelScheduledValues(startTime);
gainNode.gain.setValueAtTime(0, startTime);
gainNode.gain.linearRampToValueAtTime(1, startTime + attack);
gainNode.gain.linearRampToValueAtTime(sustain, startTime + attack + decay);
gainNode.gain.setValueAtTime(sustain, startTime + duration);
gainNode.gain.linearRampToValueAtTime(0, startTime + duration + release);
osc.stop(startTime + duration + release);
}
playChord(notes, duration, startTime) {
notes.forEach(n => {
let freq = getFrequency(n.note, n.octave);
if(!freq) freq = 0;
if(freq!==0) this.playNote(freq, duration, startTime);
});
}
}
const expSynth = new ExportSynth(offlineCtx, {adsr: ADSR, waveform, pulseWidth, filterCutoff});
expSynth.masterGain.gain.value = 0.5;
let currentTime = 0;
for(let i = 0; i < (loopCheckbox.checked ? 2 : 1); i++) {
for(let item of sequence) {
expSynth.playChord(item.notes, item.duration, currentTime);
currentTime += item.duration;
}
}
let renderedBuffer = await offlineCtx.startRendering();
// WAV export helper
function bufferToWav(buffer) {
let numOfChan = buffer.numberOfChannels,
length = buffer.length * numOfChan * 2 + 44,
bufferArray = new ArrayBuffer(length),
view = new DataView(bufferArray),
channels = [],
i, sample,
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(buffer.sampleRate);
setUint32(buffer.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(i = 0; i < buffer.numberOfChannels; i++)
channels.push(buffer.getChannelData(i));
while(pos < length) {
for(i = 0; i < numOfChan; i++) { // interleave channels
sample = Math.max(-1, Math.min(1, channels[i][offset])); // clamp
sample = (sample < 0 ? sample * 0x8000 : sample * 0x7FFF) | 0;
view.setInt16(pos, sample, true); // little endian
pos += 2;
}
offset++;
}
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;
}
}
let wavBlob = bufferToWav(renderedBuffer);
let url = URL.createObjectURL(wavBlob);
let a = document.createElement("a");
a.href = url;
a.download = "rtttl_export.wav";
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
logEl.textContent = "Export finished.";
});
})();
</script>
</body>
</html>