Use oscillators and filters (with pulse width control),
Update synth parameters on the fly,
Share or export the sound,
Export audio as WAV files,
And possibly manage some UI with tags like "#/" (not entirely clear what that refers to but might be markdown or UI identifiers).
I will provide a solid foundational example in HTML and JavaScript that includes:
An RTTTL parser supporting chords,
A simple Web Audio API synth with ADSR and pulse-width modulation,
Looping playback,
Export to WAV,
A share link generation (via URL or textarea),
Copy-to-clipboard functionality.
Overview of the proposed approach:
RTTTL Parsing: We'll parse the RTTTL string to extract notes and durations, including chords specified via +.
Synth Implementation: We'll use Web Audio API oscillators combined in a gain node to play multiple notes simultaneously (for chords).
ADSR: Using GainNode envelope with configurable ADSR parameters.
Pulse Width: For the pulse oscillator, we'll approximate pulse wave by using a PeriodicWave or by combining oscillators. But a simplest approach is to use the OscillatorNode with "square" type and then modulate pulse width with Gain node or use setPeriodicWave. (Web Audio doesn't provide direct pulse width modulation in built-in oscillator)
Filter: We'll add a BiquadFilterNode.
Export WAV: Using OfflineAudioContext to render the audio offline and export as WAV buffer.
Copy & Share: Copy the RTTTL or shareable link to clipboard.
Full working example below
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>RTTTL Synth</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
textarea { width: 100%; height: 100px; font-family: monospace; }
label { display: block; margin-top: 10px; }
input[type="range"] { width: 100%; }
button { margin-top: 10px; }
#log { margin-top: 10px; color: green; }
</style>
</head>
<body>
<h1>RTTTL Synthesizer</h1>
<label for="rtttl-input">RTTTL Input</label>
<textarea id="rtttl-input" spellcheck="false">Enter or paste RTTTL string here.</textarea>
<label for="adsr-attack">ADSR Attack (sec)</label>
<input type="range" id="adsr-attack" min="0" max="2" step="0.01" value="0.1" />
<span id="adsr-attack-val">0.1</span>
<label for="adsr-decay">ADSR Decay (sec)</label>
<input type="range" id="adsr-decay" min="0" max="2" step="0.01" value="0.1" />
<span id="adsr-decay-val">0.1</span>
<label for="adsr-sustain">ADSR Sustain (0-1)</label>
<input type="range" id="adsr-sustain" min="0" max="1" step="0.01" value="0.8" />
<span id="adsr-sustain-val">0.8</span>
<label for="adsr-release">ADSR Release (sec)</label>
<input type="range" id="adsr-release" min="0" max="3" step="0.01" value="0.5" />
<span id="adsr-release-val">0.5</span>
<label for="pulse-width">Pulse Width (%)</label>
<input type="range" id="pulse-width" min="1" max="99" step="1" value="50" />
<span id="pulse-width-val">50%</span>
<label for="filter-cutoff">Filter Cutoff Frequency (Hz)</label>
<input type="range" id="filter-cutoff" min="100" max="10000" step="1" value="5000" />
<span id="filter-cutoff-val">5000 Hz</span>
<label><input type="checkbox" id="loop" /> Loop playback</label>
<button id="play-btn">Play</button>
<button id="stop-btn" disabled>Stop</button>
<button id="copy-btn">Copy RTTTL to Clipboard</button>
<button id="export-btn">Export WAV</button>
<label for="share-link">Share RTTTL</label>
<textarea id="share-link" readonly></textarea>
<div id="log"></div>
<script>
// Utility: note frequencies
const noteFreq = (() => {
// Notes A-G sharps/flats and octave
// base frequencies for octave 4
const baseFreqs = {
'c': 261.63,
'c#': 277.18,
'd': 293.66,
'd#': 311.13,
'e': 329.63,
'f': 349.23,
'f#': 369.99,
'g': 392.00,
'g#': 415.30,
'a': 440,
'a#': 466.16,
'b': 493.88
};
// Function to shift octaves
return function(note, octave){
note = note.toLowerCase();
let key = note;
if(note.length > 1 && (note[1] === '#' || note[1] === 'b')){
key = note[0] + (note[1]==='b' ? '#' : note[1]); // convert flat to sharp approx
if(note[1]==='b'){
// flats - approximate by lowering note
// in this version we just treat b as #
// This can be refined.
}
if(!(key in baseFreqs)){
// fallback to base letter
key = note[0];
}
}
// Adjust for flat notes:
if(note.length > 1 && note[1]==='b'){
// flat: one semitone down
// for simplicity, compute freq one semitone down
let freq = baseFreqs[note[0].toLowerCase()] || 440;
freq = freq / Math.pow(2, 1/12);
return freq * Math.pow(2, octave - 4);
}
if(!(key in baseFreqs)){
return 440 * Math.pow(2, octave - 4); // default to A4 freq
}
return baseFreqs[key] * Math.pow(2, octave - 4);
};
})();
// RTTTL Parser that supports chords and durations
// Format: name:d=4,o=5,b=140:16d+16f+16a,8p,4g
function parseRTTTL(rtttl){
// Split on :
const parts = rtttl.trim().split(':');
if(parts.length !== 3) throw new Error("Invalid RTTTL format");
const [name, defaultsStr, notesStr] = parts;
// Parse defaults
// d=duration, o=octave, b=tempo
const defaults = { d:4, o:6, b:63 };
defaultsStr.split(',').forEach(pair=>{
const [k,v] = pair.split('=');
if(k && v) defaults[k.trim()] = isNaN(v) ? v.trim() : +v;
});
const bpm = defaults.b; // beats per minute
const wholenoteDuration = (60 / bpm) * 4; // duration of whole note in seconds
// Parse notes
// notes separated by comma
// notes can be chords with '+' join
const notes = [];
const rawNotes = notesStr.split(',');
for(let rawNote of rawNotes){
// Example chord: "16d+16f+16a"
// Example note: "8p" (pause)
// Parse each note or chord component
const chordParts = rawNote.split('+');
const chord = [];
for(let notePart of chordParts){
let duration = defaults.d;
let octave = defaults.o;
let noteStr = notePart.toLowerCase();
// Extract duration if any (numbers at start)
let durationMatch = noteStr.match(/^\d+/);
if(durationMatch){
duration = +durationMatch[0];
noteStr = noteStr.slice(durationMatch[0].length);
}
// Extract note, 'p' for pause
let noteCharMatch = noteStr.match(/^([a-gp])(#{0,1}|b{0,1})/);
if(!noteCharMatch){
throw new Error("Invalid note: " + notePart);
}
let noteChar = noteCharMatch[1];
let accidental = noteCharMatch[2] || '';
noteStr = noteStr.slice(noteChar.length + accidental.length);
// Extract octave if present
if(noteStr.length > 0 && !isNaN(noteStr[0])){
octave = +noteStr[0];
}
// Compute note duration in seconds
let noteDuration = wholenoteDuration / duration;
// dotted notes: check for dot after note
if(notePart.includes('.')){
noteDuration *= 1.5;
}
// Also if pause note
if(noteChar === 'p'){
chord.push({ freq: null, duration: noteDuration });
} else {
// Compute freq
let freq = noteFreq(noteChar + accidental, octave);
chord.push({ freq, duration: noteDuration });
}
}
// Add chord with durations (all same duration)
// The RTTTL by standard defines each chord's notes with same duration
// So all notes share the same duration
notes.push({ chord, duration: chord[0].duration });
}
return {
name,
defaults,
bpm,
notes
};
}
// Synth class
class Synth {
constructor(context){
this.context = context;
this.adsr = { attack:0.1, decay:0.1, sustain:0.8, release:0.5 };
this.pulseWidth = 0.5;
this.filterCutoff = 5000;
this.isPlaying = false;
this.loop = false;
this.timeoutIds = [];
}
setADSR(adsr){
this.adsr = adsr;
}
setPulseWidth(pw){
this.pulseWidth = pw;
}
setFilterCutoff(freq){
this.filterCutoff = freq;
if(this.filter){
this.filter.frequency.setTargetAtTime(freq, this.context.currentTime, 0.01);
}
}
setLoop(loop){
this.loop = loop;
}
_makePulseOscillator(freq){
// WebAudio doesn't have direct pulse wave oscillator with adjustable pulse width
// We create one using two oscillators (sawtooth + phase shifted sawtooth) or periodic wave
// For simplicity, here's a simple pulse oscillator approximated by periodicWave
// We create a periodic wave with harmonics of a pulse wave
// Additionally, you could create PWM via gain modulation
const real = new Float32Array([0, 4]); // 2 harmonics: 0 and 1st harmonic
const imag = new Float32Array([0, 0]);
// For adjustable pulse width, we generate harmonic coefficients accordingly
// This is an approximation.
const pw = this.pulseWidth; // 0..1, e.g. 0.5 is square
// Build Fourier series coefficients for pulse wave:
// pulse wave Fourier series coef:
// ak = 2/p * sin(k*pi*p), bk=0 where p is pulse width
// For simplicity we use a few harmonics
const harmonics = 8;
let realH = new Float32Array(harmonics+1);
let imagH = new Float32Array(harmonics+1);
realH[0] = 0;
imagH[0] = 0;
for(let n=1;n<=harmonics;n++){
realH[n] = 2/pw * Math.sin(n*Math.PI*pw)/ (n*Math.PI);
imagH[n] = 0; // no imaginary part for pulse wave
}
const wave = this.context.createPeriodicWave(realH, imagH, {disableNormalization: true});
const osc = this.context.createOscillator();
osc.frequency.value = freq;
osc.setPeriodicWave(wave);
return osc;
}
_playNote(freq, duration, startTime){
if(freq === null){
// Pause
return Promise.resolve(duration);
}
const ctx = this.context;
const osc = this._makePulseOscillator(freq);
const gainNode = ctx.createGain();
const filter = ctx.createBiquadFilter();
filter.type = 'lowpass';
filter.frequency.value = this.filterCutoff;
osc.connect(filter);
filter.connect(gainNode);
gainNode.connect(ctx.destination);
const now = startTime;
// ADSR envelope
let a = this.adsr.attack;
let d = this.adsr.decay;
let s = this.adsr.sustain;
let r = this.adsr.release;
gainNode.gain.setValueAtTime(0, now);
gainNode.gain.linearRampToValueAtTime(1, now + a);
gainNode.gain.linearRampToValueAtTime(s, now + a + d);
// Sustain until release time
osc.start(now);
// Start release at (now + duration - r)
gainNode.gain.setValueAtTime(s, now + duration - r);
gainNode.gain.linearRampToValueAtTime(0, now + duration);
osc.stop(now + duration + 0.1);
return duration;
}
play(rtttl){
if(this.isPlaying) return;
this.isPlaying = true;
let parsed;
try {
parsed = parseRTTTL(rtttl);
} catch(e){
alert("Error parsing RTTTL: " + e.message);
this.isPlaying = false;
return;
}
const ctx = this.context;
let time = ctx.currentTime + 0.1; // slight delay before start
const playNotes = () => {
if(!this.isPlaying) return;
for(let {chord, duration} of parsed.notes){
for(let note of chord){
if(note.freq !== null){
this._playNote(note.freq, duration, time);
}
}
time += duration;
}
if(this.loop){
// Schedule next loop
this.loopTimeout = setTimeout(() => {
playNotes();
}, (time - ctx.currentTime)*1000);
} else {
// Stop flag after notes end
setTimeout(() => {
this.isPlaying = false;
document.getElementById('play-btn').disabled = false;
document.getElementById('stop-btn').disabled = true;
log("Playback finished.");
}, (time - ctx.currentTime)*1000);
}
};
playNotes();
}
stop(){
if(!this.isPlaying) return;
this.isPlaying = false;
if(this.loopTimeout){
clearTimeout(this.loopTimeout);
this.loopTimeout = null;
}
document.getElementById('play-btn').disabled = false;
document.getElementById('stop-btn').disabled = true;
log('Playback stopped.');
}
async exportWav(rtttl){
let parsed;
try {
parsed = parseRTTTL(rtttl);
} catch(e){
alert("Error parsing RTTTL: " + e.message);
return;
}
// Estimate total duration
const totalDuration = parsed.notes.reduce((acc,n)=>acc+n.duration, 0) + this.adsr.release;
const sampleRate = 44100;
const offlineCtx = new OfflineAudioContext(1, sampleRate * totalDuration, sampleRate);
// We recreate synth for offline context
const adsr = this.adsr;
const pulseWidth = this.pulseWidth;
const filterCutoff = this.filterCutoff;
// custom method to make pulse oscillator in offline ctx
const makePulseOscillator = (freq) => {
const harmonics = 8;
let realH = new Float32Array(harmonics+1);
let imagH = new Float32Array(harmonics+1);
realH[0] = 0;
imagH[0] = 0;
for(let n=1;n<=harmonics;n++){
realH[n] = 2/pulseWidth * Math.sin(n*Math.PI*pulseWidth)/ (n*Math.PI);
imagH[n] = 0;
}
const wave = offlineCtx.createPeriodicWave(realH, imagH, {disableNormalization: true});
const osc = offlineCtx.createOscillator();
osc.frequency.value = freq;
osc.setPeriodicWave(wave);
return osc;
};
let currentTime = 0;
for(let {chord, duration} of parsed.notes){
for(let note of chord){
if(note.freq === null) continue; // pause
const osc = makePulseOscillator(note.freq);
const gainNode = offlineCtx.createGain();
const filter = offlineCtx.createBiquadFilter();
filter.type = 'lowpass';
filter.frequency.value = filterCutoff;
osc.connect(filter);
filter.connect(gainNode);
gainNode.connect(offlineCtx.destination);
const now = currentTime;
gainNode.gain.setValueAtTime(0, now);
gainNode.gain.linearRampToValueAtTime(1, now + adsr.attack);
gainNode.gain.linearRampToValueAtTime(adsr.sustain, now + adsr.attack + adsr.decay);
osc.start(now);
gainNode.gain.setValueAtTime(adsr.sustain, now + duration - adsr.release);
gainNode.gain.linearRampToValueAtTime(0, now + duration);
osc.stop(now + duration + 0.1);
}
currentTime += duration;
}
const renderedBuffer = await offlineCtx.startRendering();
// Convert AudioBuffer to WAV
const wav = audioBufferToWav(renderedBuffer);
// Download wav
const blob = new Blob([new DataView(wav)], {type: 'audio/wav'});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = parsed.name + '.wav';
a.click();
URL.revokeObjectURL(url);
log("Exported WAV: " + parsed.name + ".wav");
}
}
// Convert AudioBuffer to WAV file (8 or 16 bit PCM)
// https://github.com/Jam3/audiobuffer-to-wav/blob/master/index.js
function audioBufferToWav(buffer, opt) {
opt = opt || {}
var numChannels = buffer.numberOfChannels
var sampleRate = buffer.sampleRate
var format = opt.float32 ? 3 : 1
var bitDepth = format === 3 ? 32 : 16
var result
if (numChannels === 2) {
result = interleave(buffer.getChannelData(0), buffer.getChannelData(1))
} else {
result = buffer.getChannelData(0)
}
return encodeWAV(result, format, sampleRate, numChannels, bitDepth)
}
function interleave(inputL, inputR) {
var length = inputL.length + inputR.length
var result = new Float32Array(length)
var index = 0
var inputIndex = 0
while (index < length) {
result[index++] = inputL[inputIndex]
result[index++] = inputR[inputIndex]
inputIndex++
}
return result
}
function encodeWAV(samples, format, sampleRate, numChannels, bitDepth) {
var bytesPerSample = bitDepth / 8
var blockAlign = numChannels * bytesPerSample
var buffer = new ArrayBuffer(44 + samples.length * bytesPerSample)
var view = new DataView(buffer)
/* RIFF identifier */
writeString(view, 0, 'RIFF')
/* file length */
view.setUint32(4, 36 + samples.length * bytesPerSample, true)
/* RIFF type */
writeString(view, 8, 'WAVE')
/* format chunk identifier */
writeString(view, 12, 'fmt ')
/* format chunk length */
view.setUint32(16, 16, true)
/* sample format (1 = PCM) */
view.setUint16(20, format, 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 * blockAlign, true)
/* block align (channel count * bytes per sample) */
view.setUint16(32, blockAlign, true)
/* bits per sample */
view.setUint16(34, bitDepth, true)
/* data chunk identifier */
writeString(view, 36, 'data')
/* data chunk length */
view.setUint32(40, samples.length * bytesPerSample, true)
if (format === 1) { // Raw PCM
floatTo16BitPCM(view, 44, samples)
} else {
writeFloat32(view, 44, samples)
}
return buffer
}
function writeFloat32(output, offset, input) {
for (var i = 0; i < input.length; i++, offset += 4) {
output.setFloat32(offset, input[i], true)
}
}
function floatTo16BitPCM(output, offset, input) {
for (var i = 0; i < input.length; i++, offset += 2) {
var s = Math.max(-1, Math.min(1, input[i]))
output.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true)
}
}
function writeString(view, offset, string) {
for (var i = 0; i < string.length; i++) {
view.setUint8(offset + i, string.charCodeAt(i))
}
}
// Clipboard copy
function copyToClipboard(text){
navigator.clipboard.writeText(text).then(() => {
log('Copied to clipboard.');
}).catch(err=>{
log('Failed to copy: ' + err);
});
}
function log(msg){
const logElem = document.getElementById('log');
logElem.textContent = msg;
}
// UI and event handlers
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
let synth = new Synth(audioContext);
document.getElementById('play-btn').addEventListener('click', e=>{
if(audioContext.state === 'suspended'){
audioContext.resume();
}
const rtttl = document.getElementById('rtttl-input').value.trim();
synth.setLoop(document.getElementById('loop').checked);
synth.play(rtttl);
e.target.disabled = true;
document.getElementById('stop-btn').disabled = false;
log("Playing...");
});
document.getElementById('stop-btn').addEventListener('click', e=>{
synth.stop();
});
document.getElementById('copy-btn').addEventListener('click', e=>{
const rtttl = document.getElementById('rtttl-input').value.trim();
if(!rtttl) return;
copyToClipboard(rtttl);
});
document.getElementById('export-btn').addEventListener('click', async e=>{
const rtttl = document.getElementById('rtttl-input').value.trim();
if(!rtttl) return;
log("Exporting WAV, please wait...");
await synth.exportWav(rtttl);
});
// Update ADSR displays and synth ADSR params
['attack','decay','sustain','release'].forEach(param => {
const slider = document.getElementById('adsr-' + param);
const display = document.getElementById('adsr-' + param + '-val');
slider.addEventListener('input', ()=>{
let val = param==='sustain' ? parseFloat(slider.value).toFixed(2) : parseFloat(slider.value).toFixed(2);
if(param === 'sustain'){
display.textContent = val;
} else {
display.textContent = val + " sec";
}
const adsr = {
attack: +document.getElementById('adsr-attack').value,
decay: +document.getElementById('adsr-decay').value,
sustain: +document.getElementById('adsr-sustain').value,
release: +document.getElementById('adsr-release').value,
};
synth.setADSR(adsr);
});
});
// Pulse width control
const pulseSlider = document.getElementById('pulse-width');
const pulseDisplay = document.getElementById('pulse-width-val');
pulseSlider.addEventListener('input', ()=>{
pulseDisplay.textContent = pulseSlider.value + '%';
synth.setPulseWidth(+pulseSlider.value / 100);
});
// Filter cutoff control
const filterSlider = document.getElementById('filter-cutoff');
const filterDisplay = document.getElementById('filter-cutoff-val');
filterSlider.addEventListener('input', ()=>{
filterDisplay.textContent = filterSlider.value + " Hz";
synth.setFilterCutoff(+filterSlider.value);
});
// Share link generation (encode RTTTL in URL hash)
const shareTextarea = document.getElementById('share-link');
function updateShareLink(){
let rtttl = document.getElementById('rtttl-input').value.trim();
if(!rtttl){
shareTextarea.value = "";
return;
}
const encoded = encodeURIComponent(btoa(rtttl));
const url = `${location.origin}${location.pathname}#${encoded}`;
shareTextarea.value = url;
}
document.getElementById('rtttl-input').addEventListener('input', updateShareLink);
updateShareLink();
// On page load check if hash exists
window.addEventListener('load', ()=>{
if(location.hash.length > 1){
try {
const decoded = atob(decodeURIComponent(location.hash.substring(1)));
document.getElementById('rtttl-input').value = decoded;
updateShareLink();
} catch(e){
// ignore fail
}
}
});
</script>
</body>
</html>
Features included:
Paste/enter RTTTL string with chords using "+" sign (for example: 16d+16f+16a)
Control ADSR envelope with sliders
Pulse width percentage slider (used in custom periodic wave)
Filter cutoff frequency slider
Play / Stop buttons
Loop playback support with checkbox
Copy RTTTL text to clipboard button
Share link generated with encoded RTTTL string in URL hash (base64-encoded)
Export to WAV file button (works offline render)
Basic parsing errors are alerted
How to test chords
Example RTTTL string with chords (you can paste in the textarea):
code
Chord:d=4,o=5,b=120:8c+8e+8g,8p,8d+8f+8a,8p,4g
This plays three-note chords (C major, D minor, then G) with pauses.
If you'd like me to extend or explain any part in more detail, just ask!